text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_TEXTURE_REGISTRAR_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_TEXTURE_REGISTRAR_H_
#include <memory>
#include <mutex>
#include <unordered_map>
#include "flutter/fml/closure.h"
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/common/public/flutter_texture_registrar.h"
#include "flutter/shell/platform/windows/egl/proc_table.h"
#include "flutter/shell/platform/windows/external_texture.h"
namespace flutter {
class FlutterWindowsEngine;
// An object managing the registration of an external texture.
// Thread safety: All member methods are thread safe.
class FlutterWindowsTextureRegistrar {
public:
explicit FlutterWindowsTextureRegistrar(FlutterWindowsEngine* engine,
std::shared_ptr<egl::ProcTable> gl);
// Registers a texture described by the given |texture_info| object.
// Returns the non-zero, positive texture id or -1 on error.
int64_t RegisterTexture(const FlutterDesktopTextureInfo* texture_info);
// Attempts to unregister the texture identified by |texture_id|.
void UnregisterTexture(int64_t texture_id, fml::closure callback = nullptr);
// Notifies the engine about a new frame being available.
// Returns true on success.
bool MarkTextureFrameAvailable(int64_t texture_id);
// Attempts to populate the given |texture| by copying the
// contents of the texture identified by |texture_id|.
// Returns true on success.
bool PopulateTexture(int64_t texture_id,
size_t width,
size_t height,
FlutterOpenGLTexture* texture);
private:
FlutterWindowsEngine* engine_ = nullptr;
std::shared_ptr<egl::ProcTable> gl_;
// All registered textures, keyed by their IDs.
std::unordered_map<int64_t, std::unique_ptr<flutter::ExternalTexture>>
textures_;
std::mutex map_mutex_;
int64_t EmplaceTexture(std::unique_ptr<ExternalTexture> texture);
FML_DISALLOW_COPY_AND_ASSIGN(FlutterWindowsTextureRegistrar);
};
}; // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_FLUTTER_WINDOWS_TEXTURE_REGISTRAR_H_
| engine/shell/platform/windows/flutter_windows_texture_registrar.h/0 | {
"file_path": "engine/shell/platform/windows/flutter_windows_texture_registrar.h",
"repo_id": "engine",
"token_count": 812
} | 420 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/keyboard_key_handler.h"
#include <rapidjson/document.h>
#include <map>
#include <memory>
#include "flutter/shell/platform/common/client_wrapper/include/flutter/method_result_functions.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h"
#include "flutter/shell/platform/common/client_wrapper/include/flutter/standard_method_codec.h"
#include "flutter/shell/platform/embedder/test_utils/key_codes.g.h"
#include "flutter/shell/platform/embedder/test_utils/proc_table_replacement.h"
#include "flutter/shell/platform/windows/keyboard_utils.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/test_binary_messenger.h"
#include "flutter/fml/macros.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
static constexpr char kChannelName[] = "flutter/keyboard";
static constexpr char kGetKeyboardStateMethod[] = "getKeyboardState";
constexpr SHORT kStateMaskToggled = 0x01;
constexpr SHORT kStateMaskPressed = 0x80;
class TestFlutterKeyEvent : public FlutterKeyEvent {
public:
TestFlutterKeyEvent(const FlutterKeyEvent& src,
FlutterKeyEventCallback callback,
void* user_data)
: character_str(src.character), callback(callback), user_data(user_data) {
struct_size = src.struct_size;
timestamp = src.timestamp;
type = src.type;
physical = src.physical;
logical = src.logical;
character = character_str.c_str();
synthesized = src.synthesized;
}
TestFlutterKeyEvent(TestFlutterKeyEvent&& source)
: FlutterKeyEvent(source),
callback(std::move(source.callback)),
user_data(source.user_data) {
character = character_str.c_str();
}
FlutterKeyEventCallback callback;
void* user_data;
private:
const std::string character_str;
};
class TestKeystate {
public:
void Set(int virtual_key, bool pressed, bool toggled_on = false) {
state_[virtual_key] = (pressed ? kStateMaskPressed : 0) |
(toggled_on ? kStateMaskToggled : 0);
}
SHORT Get(int virtual_key) { return state_[virtual_key]; }
KeyboardKeyEmbedderHandler::GetKeyStateHandler Getter() {
return [this](int virtual_key) { return Get(virtual_key); };
}
private:
std::map<int, SHORT> state_;
};
UINT DefaultMapVkToScan(UINT virtual_key, bool extended) {
return MapVirtualKey(virtual_key,
extended ? MAPVK_VK_TO_VSC_EX : MAPVK_VK_TO_VSC);
}
static constexpr int kHandledScanCode = 20;
static constexpr int kHandledScanCode2 = 22;
static constexpr int kUnhandledScanCode = 21;
constexpr uint64_t kScanCodeShiftRight = 0x36;
constexpr uint64_t kScanCodeControl = 0x1D;
constexpr uint64_t kScanCodeAltLeft = 0x38;
constexpr uint64_t kScanCodeKeyA = 0x1e;
constexpr uint64_t kVirtualKeyA = 0x41;
typedef std::function<void(bool)> Callback;
typedef std::function<void(Callback&)> CallbackHandler;
void dont_respond(Callback& callback) {}
void respond_true(Callback& callback) {
callback(true);
}
void respond_false(Callback& callback) {
callback(false);
}
// A testing |KeyHandlerDelegate| that records all calls
// to |KeyboardHook| and can be customized with whether
// the hook is handled in async.
class MockKeyHandlerDelegate
: public KeyboardKeyHandler::KeyboardKeyHandlerDelegate {
public:
class KeyboardHookCall {
public:
int delegate_id;
int key;
int scancode;
int action;
char32_t character;
bool extended;
bool was_down;
std::function<void(bool)> callback;
};
// Create a |MockKeyHandlerDelegate|.
//
// The |delegate_id| is an arbitrary ID to tell between delegates
// that will be recorded in |KeyboardHookCall|.
//
// The |hook_history| will store every call to |KeyboardHookCall| that are
// handled asynchronously.
//
// The |is_async| is a function that the class calls upon every
// |KeyboardHookCall| to decide whether the call is handled asynchronously.
// Defaults to always returning true (async).
MockKeyHandlerDelegate(int delegate_id,
std::list<KeyboardHookCall>* hook_history)
: delegate_id(delegate_id),
hook_history(hook_history),
callback_handler(dont_respond) {}
virtual ~MockKeyHandlerDelegate() = default;
virtual void KeyboardHook(int key,
int scancode,
int action,
char32_t character,
bool extended,
bool was_down,
std::function<void(bool)> callback) {
hook_history->push_back(KeyboardHookCall{
.delegate_id = delegate_id,
.key = key,
.scancode = scancode,
.character = character,
.extended = extended,
.was_down = was_down,
.callback = std::move(callback),
});
callback_handler(hook_history->back().callback);
}
virtual void SyncModifiersIfNeeded(int modifiers_state) {
// Do Nothing
}
virtual std::map<uint64_t, uint64_t> GetPressedState() {
std::map<uint64_t, uint64_t> Empty_State;
return Empty_State;
}
CallbackHandler callback_handler;
int delegate_id;
std::list<KeyboardHookCall>* hook_history;
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockKeyHandlerDelegate);
};
enum KeyEventResponse {
kNoResponse,
kHandled,
kUnhandled,
};
static KeyEventResponse key_event_response = kNoResponse;
void OnKeyEventResult(bool handled) {
key_event_response = handled ? kHandled : kUnhandled;
}
void SimulateKeyboardMessage(TestBinaryMessenger* messenger,
const std::string& method_name,
std::unique_ptr<EncodableValue> arguments,
MethodResult<EncodableValue>* result_handler) {
MethodCall<> call(method_name, std::move(arguments));
auto message = StandardMethodCodec::GetInstance().EncodeMethodCall(call);
EXPECT_TRUE(messenger->SimulateEngineMessage(
kChannelName, message->data(), message->size(),
[&result_handler](const uint8_t* reply, size_t reply_size) {
StandardMethodCodec::GetInstance().DecodeAndProcessResponseEnvelope(
reply, reply_size, result_handler);
}));
}
} // namespace
using namespace ::flutter::testing::keycodes;
TEST(KeyboardKeyHandlerTest, SingleDelegateWithAsyncResponds) {
std::list<MockKeyHandlerDelegate::KeyboardHookCall> hook_history;
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
KeyboardKeyHandler handler(&messenger);
// Add one delegate
auto delegate = std::make_unique<MockKeyHandlerDelegate>(1, &hook_history);
handler.AddDelegate(std::move(delegate));
/// Test 1: One event that is handled by the framework
// Dispatch a key event
handler.KeyboardHook(64, kHandledScanCode, WM_KEYDOWN, L'a', false, true,
OnKeyEventResult);
EXPECT_EQ(key_event_response, kNoResponse);
EXPECT_EQ(hook_history.size(), 1);
EXPECT_EQ(hook_history.back().delegate_id, 1);
EXPECT_EQ(hook_history.back().scancode, kHandledScanCode);
EXPECT_EQ(hook_history.back().was_down, true);
EXPECT_EQ(key_event_response, kNoResponse);
hook_history.back().callback(true);
EXPECT_EQ(key_event_response, kHandled);
key_event_response = kNoResponse;
hook_history.clear();
/// Test 2: Two events that are unhandled by the framework
handler.KeyboardHook(64, kHandledScanCode, WM_KEYDOWN, L'a', false, false,
OnKeyEventResult);
EXPECT_EQ(key_event_response, kNoResponse);
EXPECT_EQ(hook_history.size(), 1);
EXPECT_EQ(hook_history.back().delegate_id, 1);
EXPECT_EQ(hook_history.back().scancode, kHandledScanCode);
EXPECT_EQ(hook_history.back().was_down, false);
// Dispatch another key event
handler.KeyboardHook(65, kHandledScanCode2, WM_KEYUP, L'b', false, true,
OnKeyEventResult);
EXPECT_EQ(key_event_response, kNoResponse);
EXPECT_EQ(hook_history.size(), 2);
EXPECT_EQ(hook_history.back().delegate_id, 1);
EXPECT_EQ(hook_history.back().scancode, kHandledScanCode2);
EXPECT_EQ(hook_history.back().was_down, true);
// Resolve the second event first to test out-of-order response
hook_history.back().callback(false);
EXPECT_EQ(key_event_response, kUnhandled);
key_event_response = kNoResponse;
// Resolve the first event then
hook_history.front().callback(false);
EXPECT_EQ(key_event_response, kUnhandled);
hook_history.clear();
key_event_response = kNoResponse;
}
TEST(KeyboardKeyHandlerTest, SingleDelegateWithSyncResponds) {
std::list<MockKeyHandlerDelegate::KeyboardHookCall> hook_history;
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
KeyboardKeyHandler handler(&messenger);
// Add one delegate
auto delegate = std::make_unique<MockKeyHandlerDelegate>(1, &hook_history);
CallbackHandler& delegate_handler = delegate->callback_handler;
handler.AddDelegate(std::move(delegate));
/// Test 1: One event that is handled by the framework
// Dispatch a key event
delegate_handler = respond_true;
handler.KeyboardHook(64, kHandledScanCode, WM_KEYDOWN, L'a', false, false,
OnKeyEventResult);
EXPECT_EQ(key_event_response, kHandled);
EXPECT_EQ(hook_history.size(), 1);
EXPECT_EQ(hook_history.back().delegate_id, 1);
EXPECT_EQ(hook_history.back().scancode, kHandledScanCode);
EXPECT_EQ(hook_history.back().was_down, false);
hook_history.clear();
/// Test 2: An event unhandled by the framework
delegate_handler = respond_false;
handler.KeyboardHook(64, kHandledScanCode, WM_KEYDOWN, L'a', false, false,
OnKeyEventResult);
EXPECT_EQ(key_event_response, kUnhandled);
EXPECT_EQ(hook_history.size(), 1);
EXPECT_EQ(hook_history.back().delegate_id, 1);
EXPECT_EQ(hook_history.back().scancode, kHandledScanCode);
EXPECT_EQ(hook_history.back().was_down, false);
hook_history.clear();
key_event_response = kNoResponse;
}
TEST(KeyboardKeyHandlerTest, HandlerGetPressedState) {
TestKeystate key_state;
TestBinaryMessenger messenger([](const std::string& channel,
const uint8_t* message, size_t message_size,
BinaryReply reply) {});
KeyboardKeyHandler handler(&messenger);
std::unique_ptr<KeyboardKeyEmbedderHandler> embedder_handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[](const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* user_data) {},
key_state.Getter(), DefaultMapVkToScan);
handler.AddDelegate(std::move(embedder_handler));
// Dispatch a key event.
handler.KeyboardHook(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false,
false, OnKeyEventResult);
std::map<uint64_t, uint64_t> pressed_state = handler.GetPressedState();
EXPECT_EQ(pressed_state.size(), 1);
EXPECT_EQ(pressed_state.at(kPhysicalKeyA), kLogicalKeyA);
}
TEST(KeyboardKeyHandlerTest, KeyboardChannelGetPressedState) {
TestKeystate key_state;
TestBinaryMessenger messenger;
KeyboardKeyHandler handler(&messenger);
std::unique_ptr<KeyboardKeyEmbedderHandler> embedder_handler =
std::make_unique<KeyboardKeyEmbedderHandler>(
[](const FlutterKeyEvent& event, FlutterKeyEventCallback callback,
void* user_data) {},
key_state.Getter(), DefaultMapVkToScan);
handler.AddDelegate(std::move(embedder_handler));
handler.InitKeyboardChannel();
// Dispatch a key event.
handler.KeyboardHook(kVirtualKeyA, kScanCodeKeyA, WM_KEYDOWN, 'a', false,
false, OnKeyEventResult);
bool success = false;
MethodResultFunctions<> result_handler(
[&success](const EncodableValue* result) {
success = true;
auto& map = std::get<EncodableMap>(*result);
EXPECT_EQ(map.size(), 1);
EncodableValue physical_value(static_cast<long long>(kPhysicalKeyA));
EncodableValue logical_value(static_cast<long long>(kLogicalKeyA));
EXPECT_EQ(map.at(physical_value), logical_value);
},
nullptr, nullptr);
SimulateKeyboardMessage(&messenger, kGetKeyboardStateMethod, nullptr,
&result_handler);
EXPECT_TRUE(success);
}
} // namespace testing
} // namespace flutter
| engine/shell/platform/windows/keyboard_key_handler_unittests.cc/0 | {
"file_path": "engine/shell/platform/windows/keyboard_key_handler_unittests.cc",
"repo_id": "engine",
"token_count": 5010
} | 421 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_SEQUENTIAL_ID_GENERATOR_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_SEQUENTIAL_ID_GENERATOR_H_
#include <cstdint>
#include <unordered_map>
#include "flutter/fml/macros.h"
namespace flutter {
// This is used to generate a series of sequential ID numbers in a way that a
// new ID is always the lowest possible ID in the sequence.
//
// based on
// https://source.chromium.org/chromium/chromium/src/+/main:ui/gfx/sequential_id_generator.h
class SequentialIdGenerator {
public:
// Creates a new generator with the specified lower bound and uppoer bound for
// the IDs.
explicit SequentialIdGenerator(uint32_t min_id, uint32_t max_id);
~SequentialIdGenerator();
// Generates a unique ID to represent |number|. The generated ID is the
// smallest available ID greater than or equal to the |min_id| specified
// during creation of the generator.
uint32_t GetGeneratedId(uint32_t number);
// Checks to see if the generator currently has a unique ID generated for
// |number|.
bool HasGeneratedIdFor(uint32_t number) const;
// Removes the ID previously generated for |number| by calling
// |GetGeneratedID()| - does nothing if the number is not mapped.
void ReleaseNumber(uint32_t number);
// Releases ID previously generated by calling |GetGeneratedID()|. Does
// nothing if the ID is not mapped.
void ReleaseId(uint32_t id);
private:
typedef std::unordered_map<uint32_t, uint32_t> IdMap;
uint32_t GetNextAvailableId();
void UpdateNextAvailableIdAfterRelease(uint32_t id);
IdMap number_to_id_;
IdMap id_to_number_;
const uint32_t min_id_;
const uint32_t max_id_;
uint32_t min_available_id_;
FML_DISALLOW_COPY_AND_ASSIGN(SequentialIdGenerator);
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_SEQUENTIAL_ID_GENERATOR_H_
| engine/shell/platform/windows/sequential_id_generator.h/0 | {
"file_path": "engine/shell/platform/windows/sequential_id_generator.h",
"repo_id": "engine",
"token_count": 656
} | 422 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/windows/egl/window_surface.h"
#include "gmock/gmock.h"
namespace flutter {
namespace testing {
namespace egl {
/// Mock for the |WindowSurface| base class.
class MockWindowSurface : public flutter::egl::WindowSurface {
public:
MockWindowSurface()
: WindowSurface(EGL_NO_DISPLAY, EGL_NO_CONTEXT, EGL_NO_SURFACE, 0, 0) {}
MOCK_METHOD(bool, IsValid, (), (const, override));
MOCK_METHOD(bool, Destroy, (), (override));
MOCK_METHOD(bool, MakeCurrent, (), (const, override));
MOCK_METHOD(bool, SwapBuffers, (), (const, override));
MOCK_METHOD(bool, SetVSyncEnabled, (bool), (override));
private:
FML_DISALLOW_COPY_AND_ASSIGN(MockWindowSurface);
};
} // namespace egl
} // namespace testing
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_EGL_MOCK_WINDOW_SURFACE_H_
| engine/shell/platform/windows/testing/egl/mock_window_surface.h/0 | {
"file_path": "engine/shell/platform/windows/testing/egl/mock_window_surface.h",
"repo_id": "engine",
"token_count": 443
} | 423 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_
#include <windows.h>
#include <functional>
#include <string>
#include "flutter/fml/macros.h"
#include "flutter/shell/platform/embedder/embedder.h"
#include "flutter/shell/platform/windows/testing/engine_modifier.h"
#include "flutter/shell/platform/windows/testing/wm_builders.h"
#include "gtest/gtest.h"
struct _FlutterPlatformMessageResponseHandle {
FlutterDesktopBinaryReply callback;
void* user_data;
};
namespace flutter {
namespace testing {
::testing::AssertionResult _EventEquals(const char* expr_event,
const char* expr_expected,
const FlutterKeyEvent& event,
const FlutterKeyEvent& expected);
// Clone string onto the heap.
//
// If #string is nullptr, returns nullptr. Otherwise, the returned pointer must
// be freed with delete[].
char* clone_string(const char* string);
// Creates a valid Windows LPARAM for WM_KEYDOWN and WM_CHAR from parameters
// given.
//
// While |CreateKeyEventLparam| is flexible, it's recommended to use dedicated
// functions in wm_builders.h, such as |WmKeyDownInfo|.
LPARAM CreateKeyEventLparam(USHORT scancode,
bool extended,
bool was_down,
USHORT repeat_count = 1,
bool context_code = 0,
bool transition_state = 1);
class MockKeyResponseController {
public:
using ResponseCallback = std::function<void(bool)>;
using EmbedderCallbackHandler =
std::function<void(const FlutterKeyEvent*, ResponseCallback)>;
using ChannelCallbackHandler = std::function<void(ResponseCallback)>;
using TextInputCallbackHandler =
std::function<void(std::unique_ptr<rapidjson::Document>)>;
MockKeyResponseController()
: channel_response_(ChannelRespondFalse),
embedder_response_(EmbedderRespondFalse),
text_input_response_(
[](std::unique_ptr<rapidjson::Document> document) {}) {}
void SetChannelResponse(ChannelCallbackHandler handler) {
channel_response_ = std::move(handler);
}
void SetEmbedderResponse(EmbedderCallbackHandler handler) {
embedder_response_ = std::move(handler);
}
void SetTextInputResponse(TextInputCallbackHandler handler) {
text_input_response_ = std::move(handler);
}
void HandleChannelMessage(ResponseCallback callback) {
channel_response_(callback);
}
void HandleEmbedderMessage(const FlutterKeyEvent* event,
ResponseCallback callback) {
embedder_response_(event, std::move(callback));
}
void HandleTextInputMessage(std::unique_ptr<rapidjson::Document> document) {
text_input_response_(std::move(document));
}
private:
EmbedderCallbackHandler embedder_response_;
ChannelCallbackHandler channel_response_;
TextInputCallbackHandler text_input_response_;
static void ChannelRespondFalse(ResponseCallback callback) {
callback(false);
}
static void EmbedderRespondFalse(const FlutterKeyEvent* event,
ResponseCallback callback) {
callback(false);
}
FML_DISALLOW_COPY_AND_ASSIGN(MockKeyResponseController);
};
void MockEmbedderApiForKeyboard(
EngineModifier& modifier,
std::shared_ptr<MockKeyResponseController> response_controller);
// Simulate a message queue for WM messages.
//
// Subclasses must implement |Win32SendMessage| for how dispatched messages are
// processed.
class MockMessageQueue {
protected:
// Push a message to the message queue without dispatching it.
void PushBack(const Win32Message* message);
// Dispatch the first message of the message queue and return its result.
//
// This method asserts that the queue is not empty.
LRESULT DispatchFront();
// Peak the next message in the message queue.
//
// See Win32's |PeekMessage| for documentation.
BOOL Win32PeekMessage(LPMSG lpMsg,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
UINT wRemoveMsg);
// Simulate dispatching a message to the system.
virtual LRESULT Win32SendMessage(UINT const message,
WPARAM const wparam,
LPARAM const lparam) = 0;
std::list<Win32Message> _pending_messages;
std::list<Win32Message> _sent_messages;
};
} // namespace testing
} // namespace flutter
// Expect the |_target| FlutterKeyEvent has the required properties.
#define EXPECT_EVENT_EQUALS(_target, _type, _physical, _logical, _character, \
_synthesized) \
EXPECT_PRED_FORMAT2( \
_EventEquals, _target, \
(FlutterKeyEvent{ \
/* struct_size = */ sizeof(FlutterKeyEvent), \
/* timestamp = */ 0, \
/* type = */ _type, \
/* physical = */ _physical, \
/* logical = */ _logical, \
/* character = */ _character, \
/* synthesized = */ _synthesized, \
/* device_type = */ kFlutterKeyEventDeviceTypeKeyboard, \
}));
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_TESTING_TEST_KEYBOARD_H_
| engine/shell/platform/windows/testing/test_keyboard.h/0 | {
"file_path": "engine/shell/platform/windows/testing/test_keyboard.h",
"repo_id": "engine",
"token_count": 2574
} | 424 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_H_
#define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_H_
#include <windows.h>
#include <string>
#include <variant>
#include "flutter/shell/platform/common/alert_platform_node_delegate.h"
#include "flutter/shell/platform/common/geometry.h"
#include "flutter/shell/platform/windows/public/flutter_windows.h"
#include "flutter/shell/platform/windows/window_binding_handler_delegate.h"
namespace ui {
class AXPlatformNodeWin;
}
namespace flutter {
class FlutterWindowsView;
// Structure containing physical bounds of a Window
struct PhysicalWindowBounds {
size_t width;
size_t height;
};
// Structure containing the position of a mouse pointer in the coordinate system
// specified by the function where it's used.
struct PointerLocation {
size_t x;
size_t y;
};
// Abstract class for binding Windows platform windows to Flutter views.
class WindowBindingHandler {
public:
virtual ~WindowBindingHandler() = default;
// Sets the delegate used to communicate state changes from window to view
// such as key presses, mouse position updates etc.
virtual void SetView(WindowBindingHandlerDelegate* view) = 0;
// Returns the underlying HWND backing the window.
virtual HWND GetWindowHandle() = 0;
// Returns the scale factor for the backing window.
virtual float GetDpiScale() = 0;
// Returns the bounds of the backing window in physical pixels.
virtual PhysicalWindowBounds GetPhysicalWindowBounds() = 0;
// Sets the cursor that should be used when the mouse is over the Flutter
// content. See mouse_cursor.dart for the values and meanings of cursor_name.
virtual void UpdateFlutterCursor(const std::string& cursor_name) = 0;
// Sets the cursor directly from a cursor handle.
virtual void SetFlutterCursor(HCURSOR cursor) = 0;
// Invoked when the cursor/composing rect has been updated in the framework.
virtual void OnCursorRectUpdated(const Rect& rect) = 0;
// Invoked when the embedder clears the contents of this Flutter view.
//
// Returns whether the surface was successfully updated or not.
virtual bool OnBitmapSurfaceCleared() = 0;
// Invoked when the embedder provides us with new bitmap data for the contents
// of this Flutter view.
//
// Returns whether the surface was successfully updated or not.
virtual bool OnBitmapSurfaceUpdated(const void* allocation,
size_t row_bytes,
size_t height) = 0;
// Invoked when the app ends IME composing, such when the active text input
// client is cleared.
virtual void OnResetImeComposing() = 0;
// Returns the last known position of the primary pointer in window
// coordinates.
virtual PointerLocation GetPrimaryPointerLocation() = 0;
// Retrieve the delegate for the alert.
virtual AlertPlatformNodeDelegate* GetAlertDelegate() = 0;
// Retrieve the alert node.
virtual ui::AXPlatformNodeWin* GetAlert() = 0;
};
} // namespace flutter
#endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOW_BINDING_HANDLER_H_
| engine/shell/platform/windows/window_binding_handler.h/0 | {
"file_path": "engine/shell/platform/windows/window_binding_handler.h",
"repo_id": "engine",
"token_count": 990
} | 425 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <thread>
#include "flutter/fml/message_loop_impl.h"
#include "flutter/fml/thread.h"
#include "flutter/shell/profiling/sampling_profiler.h"
#include "flutter/testing/testing.h"
#include "gmock/gmock.h"
using testing::_;
using testing::Invoke;
namespace fml {
namespace {
class MockTaskRunner : public fml::TaskRunner {
public:
inline static RefPtr<MockTaskRunner> Create() {
return AdoptRef(new MockTaskRunner());
}
MOCK_METHOD(void, PostTask, (const fml::closure& task), (override));
MOCK_METHOD(void,
PostTaskForTime,
(const fml::closure& task, fml::TimePoint target_time),
(override));
MOCK_METHOD(void,
PostDelayedTask,
(const fml::closure& task, fml::TimeDelta delay),
(override));
MOCK_METHOD(bool, RunsTasksOnCurrentThread, (), (override));
MOCK_METHOD(TaskQueueId, GetTaskQueueId, (), (override));
private:
MockTaskRunner() : TaskRunner(fml::RefPtr<MessageLoopImpl>()) {}
};
} // namespace
} // namespace fml
namespace flutter {
TEST(SamplingProfilerTest, DeleteAfterStart) {
auto thread =
std::make_unique<fml::Thread>(flutter::testing::GetCurrentTestName());
auto task_runner = fml::MockTaskRunner::Create();
std::atomic<int> invoke_count = 0;
// Ignore calls to PostTask since that would require mocking out calls to
// Dart.
EXPECT_CALL(*task_runner, PostDelayedTask(_, _))
.WillRepeatedly(
Invoke([&](const fml::closure& task, fml::TimeDelta delay) {
invoke_count.fetch_add(1);
thread->GetTaskRunner()->PostTask(task);
}));
{
auto profiler = SamplingProfiler(
"profiler",
/*profiler_task_runner=*/task_runner, [] { return ProfileSample(); },
/*num_samples_per_sec=*/1000);
profiler.Start();
}
int invoke_count_at_delete = invoke_count.load();
std::this_thread::sleep_for(std::chrono::milliseconds(2)); // nyquist
ASSERT_EQ(invoke_count_at_delete, invoke_count.load());
}
} // namespace flutter
| engine/shell/profiling/sampling_profiler_unittest.cc/0 | {
"file_path": "engine/shell/profiling/sampling_profiler_unittest.cc",
"repo_id": "engine",
"token_count": 850
} | 426 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
_skia_root = "//flutter/third_party/skia"
import("$_skia_root/gn/skia.gni")
import("$_skia_root/gn/toolchain/wasm.gni")
import("$_skia_root/modules/canvaskit/canvaskit.gni")
# Defines a WASM library target.
template("canvaskit_wasm_lib") {
_vars_to_forward = [
"cflags",
"check_includes",
"ldflags",
"defines",
"deps",
"includes",
"sources",
"include_dirs",
"public_configs",
"testonly",
"visibility",
]
_lib_name = target_name
executable("${_lib_name}_js") {
forward_variables_from(invoker, _vars_to_forward)
output_extension = "js"
output_name = "${_lib_name}"
}
group("$_lib_name") {
public_deps = [ ":${_lib_name}_js" ]
}
}
canvaskit_wasm_lib("canvaskit") {
# Opted out of check_includes, due to (logically) being part of skia.
check_includes = false
deps = [ "../..:skia" ]
if (skia_canvaskit_enable_paragraph) {
deps += [
"../../modules/skparagraph:skparagraph",
"../../modules/skunicode:skunicode",
]
}
sources = [
"$_skia_root/modules/canvaskit/WasmCommon.h",
"$_skia_root/modules/canvaskit/canvaskit_bindings.cpp",
]
if (skia_canvaskit_enable_paragraph) {
sources += [
"$_skia_root/modules/canvaskit/paragraph_bindings.cpp",
"$_skia_root/modules/canvaskit/paragraph_bindings_gen.cpp",
]
}
ldflags = []
if (is_debug) {
ldflags += [
"-O0",
"-sDEMANGLE_SUPPORT=1",
"-sASSERTIONS=1",
"-sGL_ASSERTIONS=1",
"-g3",
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/debug.js"),
]
} else {
externs_path = rebase_path("$_skia_root/modules/canvaskit/externs.js")
ldflags += [
"-Oz",
"--closure=1",
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/release.js"),
"--closure-args=--externs=$externs_path",
]
}
if (skia_canvaskit_profile_build) {
ldflags += [
"--profiling-funcs",
"--closure=0",
]
}
ldflags += [ "-fno-rtti" ]
if (skia_canvaskit_enable_webgl) {
ldflags += [
"-lGL",
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/cpu.js"),
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/webgl.js"),
"-sUSE_WEBGL2=1",
"-sMAX_WEBGL_VERSION=2",
]
} else {
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/cpu.js"),
"-sUSE_WEBGL2=0",
]
}
ldflags += [
"-std=c++17",
"--bind",
"--no-entry",
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/preamble.js"),
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/color.js"),
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/memory.js"),
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/util.js"),
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/interface.js"),
]
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/paragraph.js"),
]
if (skia_canvaskit_enable_pathops) {
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/pathops.js"),
]
}
if (skia_canvaskit_enable_font) {
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/font.js"),
]
}
if (skia_canvaskit_enable_skp_serialization) {
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/skp.js"),
]
}
if (skia_canvaskit_enable_rt_shader) {
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/rt_shader.js"),
]
}
ldflags += [
"--pre-js",
rebase_path("$_skia_root/modules/canvaskit/postamble.js"),
"-sALLOW_MEMORY_GROWTH",
"-sDISABLE_EXCEPTION_CATCHING",
"-sNODEJS_CATCH_EXIT=0",
"-sDYNAMIC_EXECUTION=0",
"-sEXPORT_NAME=CanvasKitInit",
"-sEXPORTED_FUNCTIONS=[_malloc,_free]",
"-sFORCE_FILESYSTEM=0",
"-sFILESYSTEM=0",
"-sMODULARIZE",
"-sNO_EXIT_RUNTIME=1",
"-sINITIAL_MEMORY=128MB",
"-sWASM",
"-sSTRICT=1",
]
defines = []
if (is_debug) {
defines += [ "SK_DEBUG" ]
} else {
defines += [ "SK_RELEASE" ]
}
if (!is_debug && !skia_canvaskit_force_tracing) {
defines += [ "SK_DISABLE_TRACING" ]
}
defines += [
"SK_FORCE_AAA",
"SK_FORCE_8_BYTE_ALIGNMENT",
"EMSCRIPTEN_HAS_UNBOUND_TYPE_NAMES=0",
"SK_SHAPER_HARFBUZZ_AVAILABLE",
]
if (skia_canvaskit_enable_paragraph) {
defines += [ "CK_INCLUDE_PARAGRAPH" ]
}
if (skia_canvaskit_enable_skp_serialization) {
defines += [ "CK_SERIALIZE_SKP" ]
}
if (skia_enable_ganesh) {
defines += [
"SK_GANESH",
"SK_DISABLE_LEGACY_SHADERCONTEXT",
]
if (skia_canvaskit_enable_webgl) {
defines += [
"SK_GL",
"CK_ENABLE_WEBGL",
]
}
}
if (skia_canvaskit_enable_pathops) {
defines += [ "CK_INCLUDE_PATHOPS" ]
}
if (skia_canvaskit_enable_rt_shader) {
defines += [ "CK_INCLUDE_RUNTIME_EFFECT" ]
}
if (!skia_canvaskit_enable_alias_font) {
defines += [ "CK_NO_ALIAS_FONT" ]
}
if (!skia_canvaskit_enable_font) {
defines += [ "CK_NO_FONTS" ]
}
}
| engine/skia/modules/canvaskit/BUILD.gn/0 | {
"file_path": "engine/skia/modules/canvaskit/BUILD.gn",
"repo_id": "engine",
"token_count": 2650
} | 427 |
#!/usr/bin/env python3
#
# Copyright 2013 The Flutter 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 argparse
import platform
import subprocess
import shutil
import sys
import os
buildroot_dir = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..', '..'))
ARCH_SUBPATH = 'mac-arm64' if platform.processor() == 'arm' else 'mac-x64'
DSYMUTIL = os.path.join(
os.path.dirname(__file__), '..', '..', '..', 'buildtools', ARCH_SUBPATH, 'clang', 'bin',
'dsymutil'
)
out_dir = os.path.join(buildroot_dir, 'out')
def main():
parser = argparse.ArgumentParser(description='Creates FlutterEmbedder.framework for macOS')
parser.add_argument('--dst', type=str, required=True)
parser.add_argument('--arm64-out-dir', type=str, required=True)
parser.add_argument('--x64-out-dir', type=str, required=True)
parser.add_argument('--strip', action='store_true', default=False)
parser.add_argument('--dsym', action='store_true', default=False)
# TODO(godofredoc): Remove after recipes v2 have landed.
parser.add_argument('--zip', action='store_true', default=False)
args = parser.parse_args()
dst = (args.dst if os.path.isabs(args.dst) else os.path.join(buildroot_dir, args.dst))
arm64_out_dir = (
args.arm64_out_dir
if os.path.isabs(args.arm64_out_dir) else os.path.join(buildroot_dir, args.arm64_out_dir)
)
x64_out_dir = (
args.x64_out_dir
if os.path.isabs(args.x64_out_dir) else os.path.join(buildroot_dir, args.x64_out_dir)
)
fat_framework = os.path.join(dst, 'FlutterEmbedder.framework')
arm64_framework = os.path.join(arm64_out_dir, 'FlutterEmbedder.framework')
x64_framework = os.path.join(x64_out_dir, 'FlutterEmbedder.framework')
arm64_dylib = os.path.join(arm64_framework, 'FlutterEmbedder')
x64_dylib = os.path.join(x64_framework, 'FlutterEmbedder')
if not os.path.isdir(arm64_framework):
print('Cannot find macOS arm64 Framework at %s' % arm64_framework)
return 1
if not os.path.isdir(x64_framework):
print('Cannot find macOS x64 Framework at %s' % x64_framework)
return 1
if not os.path.isfile(arm64_dylib):
print('Cannot find macOS arm64 dylib at %s' % arm64_dylib)
return 1
if not os.path.isfile(x64_dylib):
print('Cannot find macOS x64 dylib at %s' % x64_dylib)
return 1
if not os.path.isfile(DSYMUTIL):
print('Cannot find dsymutil at %s' % DSYMUTIL)
return 1
shutil.rmtree(fat_framework, True)
shutil.copytree(arm64_framework, fat_framework, symlinks=True)
regenerate_symlinks(fat_framework)
fat_framework_binary = os.path.join(fat_framework, 'Versions', 'A', 'FlutterEmbedder')
# Create the arm64/x64 fat framework.
subprocess.check_call([
'lipo', arm64_dylib, x64_dylib, '-create', '-output', fat_framework_binary
])
process_framework(dst, args, fat_framework, fat_framework_binary)
return 0
def regenerate_symlinks(fat_framework):
"""Regenerates the symlinks structure.
Recipes V2 upload artifacts in CAS before integration and CAS follows symlinks.
This logic regenerates the symlinks in the expected structure.
"""
if os.path.islink(os.path.join(fat_framework, 'FlutterEmbedder')):
return
os.remove(os.path.join(fat_framework, 'FlutterEmbedder'))
shutil.rmtree(os.path.join(fat_framework, 'Headers'), True)
shutil.rmtree(os.path.join(fat_framework, 'Modules'), True)
shutil.rmtree(os.path.join(fat_framework, 'Resources'), True)
current_version_path = os.path.join(fat_framework, 'Versions', 'Current')
shutil.rmtree(current_version_path, True)
os.symlink('A', current_version_path)
os.symlink(
os.path.join('Versions', 'Current', 'FlutterEmbedder'),
os.path.join(fat_framework, 'FlutterEmbedder')
)
os.symlink(os.path.join('Versions', 'Current', 'Headers'), os.path.join(fat_framework, 'Headers'))
os.symlink(os.path.join('Versions', 'Current', 'Modules'), os.path.join(fat_framework, 'Modules'))
os.symlink(
os.path.join('Versions', 'Current', 'Resources'), os.path.join(fat_framework, 'Resources')
)
def process_framework(dst, args, fat_framework, fat_framework_binary):
if args.dsym:
dsym_out = os.path.splitext(fat_framework)[0] + '.dSYM'
subprocess.check_call([DSYMUTIL, '-o', dsym_out, fat_framework_binary])
if args.zip:
dsym_dst = os.path.join(dst, 'FlutterEmbedder.dSYM')
subprocess.check_call(['zip', '-r', '-y', 'FlutterEmbedder.dSYM.zip', '.'], cwd=dsym_dst)
dsym_final_src_path = os.path.join(dsym_dst, 'FlutterEmbedder.dSYM.zip')
dsym_final_dst_path = os.path.join(dst, 'FlutterEmbedder.dSYM.zip')
shutil.move(dsym_final_src_path, dsym_final_dst_path)
if args.strip:
# copy unstripped
unstripped_out = os.path.join(dst, 'FlutterEmbedder.unstripped')
shutil.copyfile(fat_framework_binary, unstripped_out)
subprocess.check_call(['strip', '-x', '-S', fat_framework_binary])
# Zip FlutterEmbedder.framework.
if args.zip:
framework_dst = os.path.join(dst, 'FlutterEmbedder.framework')
subprocess.check_call([
'zip',
'-r',
'-y',
'FlutterEmbedder.framework.zip',
'.',
],
cwd=framework_dst)
final_src_path = os.path.join(framework_dst, 'FlutterEmbedder.framework.zip')
final_dst_path = os.path.join(dst, 'FlutterEmbedder.framework.zip')
shutil.move(final_src_path, final_dst_path)
if __name__ == '__main__':
sys.exit(main())
| engine/sky/tools/create_embedder_framework.py/0 | {
"file_path": "engine/sky/tools/create_embedder_framework.py",
"repo_id": "engine",
"token_count": 2208
} | 428 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# To create an native activity, deps in this source set in a
# `native_activity_apk` target and make sure to add the implementation of
# `NativeActivityMain` which returns a `flutter::NativeActivity` subclass.
source_set("native_activity") {
assert(is_android)
sources = [
"native_activity.cc",
"native_activity.h",
]
public_deps = [
"//flutter/fml",
"//flutter/impeller/toolkit/android",
]
libs = [
"android",
"log",
]
}
source_set("gtest_activity") {
assert(is_android)
testonly = true
sources = [
"gtest_activity.cc",
"gtest_activity.h",
]
public_deps = [
":native_activity",
"//flutter/testing:testing_lib",
]
}
| engine/testing/android/native_activity/BUILD.gn/0 | {
"file_path": "engine/testing/android/native_activity/BUILD.gn",
"repo_id": "engine",
"token_count": 305
} | 429 |
// Copyright 2013 The Flutter 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 'dart:convert';
import 'dart:io';
import 'package:args/args.dart';
import 'package:metrics_center/metrics_center.dart';
import 'package:path/path.dart' as p;
Future<ProcessResult> runGit(
List<String> args, {
String? processWorkingDir,
}) async {
return Process.run(
'git',
args,
workingDirectory: processWorkingDir,
runInShell: true,
);
}
Future<List<String>> getGitLog() async {
final String gitRoot = p.absolute('../..');
// Somehow gitDir.currentBranch() doesn't work in Cirrus with "fatal: 'HEAD' -
// not a valid ref". Therefore, we use "git log" to get the revision manually.
final ProcessResult logResult = await runGit(
<String>['log', '--pretty=format:%H %ct', '-n', '1'],
processWorkingDir: gitRoot,
);
if (logResult.exitCode != 0) {
throw 'Unexpected exit code ${logResult.exitCode}';
}
return logResult.stdout.toString().trim().split(' ');
}
class PointsAndDate {
PointsAndDate(this.points, this.date);
final List<FlutterEngineMetricPoint> points;
final String date;
}
Future<PointsAndDate> parse(String jsonFileName) async {
final List<String> gitLog = await getGitLog();
final String gitRevision = gitLog[0];
final String gitCommitDate = gitLog[1];
final List<MetricPoint> rawPoints = await GoogleBenchmarkParser.parse(
jsonFileName,
);
final List<FlutterEngineMetricPoint> points = <FlutterEngineMetricPoint>[];
for (final MetricPoint rawPoint in rawPoints) {
points.add(FlutterEngineMetricPoint(
rawPoint.tags[kNameKey]!,
rawPoint.value!,
gitRevision,
moreTags: rawPoint.tags,
));
}
return PointsAndDate(points, gitCommitDate);
}
Future<FlutterDestination> connectFlutterDestination() async {
const String kTokenPath = 'TOKEN_PATH';
const String kGcpProject = 'GCP_PROJECT';
final Map<String, String> env = Platform.environment;
final bool isTesting = env['IS_TESTING'] == 'true';
if (env.containsKey(kTokenPath) && env.containsKey(kGcpProject)) {
return FlutterDestination.makeFromAccessToken(
File(env[kTokenPath]!).readAsStringSync(),
env[kGcpProject]!,
isTesting: isTesting,
);
}
return FlutterDestination.makeFromCredentialsJson(
jsonDecode(Platform.environment['BENCHMARK_GCP_CREDENTIALS']!)
as Map<String, dynamic>,
isTesting: isTesting,
);
}
ArgParser _serupOptions() {
final ArgParser parser = ArgParser();
parser.addOption(
'json',
mandatory: true,
help: 'Path to the benchmarks json file.',
);
parser.addFlag(
'no-upload',
help: 'Upload the parsed benchmarks.',
);
return parser;
}
Future<void> main(List<String> args) async {
final ArgParser parser = _serupOptions();
final ArgResults options = parser.parse(args);
final String json = options['json'] as String;
final PointsAndDate pointsAndDate = await parse(json);
final bool noUpload = options['no-upload'] as bool;
if (noUpload) {
return;
}
// The data will be sent to the Datastore of the GCP project specified through
// environment variable BENCHMARK_GCP_CREDENTIALS, or TOKEN_PATH/GCP_PROJECT.
// The engine Cirrus job has currently configured the GCP project to
// flutter-cirrus for test. We'll eventually migrate to flutter-infra project
// once the test is done.
final FlutterDestination destination = await connectFlutterDestination();
await destination.update(
pointsAndDate.points,
DateTime.fromMillisecondsSinceEpoch(
int.parse(pointsAndDate.date) * 1000,
isUtc: true,
),
'flutter_engine_benchmark',
);
}
| engine/testing/benchmark/bin/parse_and_send.dart/0 | {
"file_path": "engine/testing/benchmark/bin/parse_and_send.dart",
"repo_id": "engine",
"token_count": 1286
} | 430 |
// Copyright 2013 The Flutter 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 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
test('Scene.toImageSync succeeds', () async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
const Color color = Color(0xFF123456);
canvas.drawPaint(Paint()..color = color);
final Picture picture = recorder.endRecording();
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(10, 10);
builder.addPicture(const Offset(5, 5), picture);
final Scene scene = builder.build();
final Image image = scene.toImageSync(6, 8);
picture.dispose();
scene.dispose();
expect(image.width, 6);
expect(image.height, 8);
final ByteData? data = await image.toByteData();
expect(data, isNotNull);
expect(data!.lengthInBytes, 6 * 8 * 4);
expect(data.buffer.asUint8List()[0], 0x12);
expect(data.buffer.asUint8List()[1], 0x34);
expect(data.buffer.asUint8List()[2], 0x56);
expect(data.buffer.asUint8List()[3], 0xFF);
});
test('Scene.toImageSync succeeds with texture layer', () async {
final SceneBuilder builder = SceneBuilder();
builder.pushOffset(10, 10);
builder.addTexture(0, width: 10, height: 10);
final Scene scene = builder.build();
final Image image = scene.toImageSync(20, 20);
scene.dispose();
expect(image.width, 20);
expect(image.height, 20);
final ByteData? data = await image.toByteData();
expect(data, isNotNull);
expect(data!.lengthInBytes, 20 * 20 * 4);
expect(data.buffer.asUint8List()[0], 0);
expect(data.buffer.asUint8List()[1], 0);
expect(data.buffer.asUint8List()[2], 0);
expect(data.buffer.asUint8List()[3], 0);
});
test('addPicture with disposed picture does not crash', () {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint());
final Picture picture = recorder.endRecording();
picture.dispose();
assert(picture.debugDisposed);
final SceneBuilder builder = SceneBuilder();
if (assertsEnabled) {
expect(
() => builder.addPicture(Offset.zero, picture),
throwsA(isInstanceOf<AssertionError>()),
);
} else {
builder.addPicture(Offset.zero, picture);
}
final Scene scene = builder.build();
scene.dispose();
});
test('pushTransform validates the matrix', () {
final SceneBuilder builder = SceneBuilder();
final Float64List matrix4 = Float64List.fromList(<double>[
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
]);
expect(builder.pushTransform(matrix4), isNotNull);
final Float64List matrix4WrongLength = Float64List.fromList(<double>[
1, 0, 0, 0,
0, 1, 0,
0, 0, 1, 0,
0, 0, 0,
]);
assert(() {
expect(
() => builder.pushTransform(matrix4WrongLength),
expectAssertion,
);
return true;
}());
final Float64List matrix4NaN = Float64List.fromList(<double>[
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, double.nan,
]);
assert(() {
expect(
() => builder.pushTransform(matrix4NaN),
expectAssertion,
);
return true;
}());
final Float64List matrix4Infinity = Float64List.fromList(<double>[
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, double.infinity,
]);
assert(() {
expect(
() => builder.pushTransform(matrix4Infinity),
expectAssertion,
);
return true;
}());
});
test('SceneBuilder accepts typed layers', () {
final SceneBuilder builder1 = SceneBuilder();
final OpacityEngineLayer opacity1 = builder1.pushOpacity(100);
expect(opacity1, isNotNull);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
final OpacityEngineLayer opacity2 = builder2.pushOpacity(200, oldLayer: opacity1);
expect(opacity2, isNotNull);
builder2.pop();
builder2.build();
});
// Attempts to use the same layer first as `oldLayer` then in `addRetained`.
void testPushThenIllegalRetain(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
pushFunction(builder2, layer);
builder2.pop();
assert(() {
try {
builder2.addRetained(layer);
fail('Expected addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('The layer is already being used'));
}
return true;
}());
builder2.build();
}
// Attempts to use the same layer first in `addRetained` then as `oldLayer`.
void testAddRetainedThenIllegalPush(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
builder2.addRetained(layer);
assert(() {
try {
pushFunction(builder2, layer);
fail('Expected push to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('The layer is already being used'));
}
return true;
}());
builder2.build();
}
// Attempts to retain the same layer twice in the same scene.
void testDoubleAddRetained(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
builder2.addRetained(layer);
assert(() {
try {
builder2.addRetained(layer);
fail('Expected second addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('The layer is already being used'));
}
return true;
}());
builder2.build();
}
// Attempts to use the same layer as `oldLayer` twice in the same scene.
void testPushOldLayerTwice(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
pushFunction(builder2, layer);
assert(() {
try {
pushFunction(builder2, layer);
fail('Expected push to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('was previously used as oldLayer'));
}
return true;
}());
builder2.build();
}
// Attempts to use a child of a retained layer as an `oldLayer`.
void testPushChildLayerOfRetainedLayer(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
final OpacityEngineLayer childLayer = builder1.pushOpacity(123);
builder1.pop();
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
builder2.addRetained(layer);
assert(() {
try {
builder2.pushOpacity(321, oldLayer: childLayer);
fail('Expected pushOpacity to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('The layer is already being used'));
}
return true;
}());
builder2.build();
}
// Attempts to retain a layer whose child is already used as `oldLayer` elsewhere in the scene.
void testRetainParentLayerOfPushedChild(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
final OpacityEngineLayer childLayer = builder1.pushOpacity(123);
builder1.pop();
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
builder2.pushOpacity(234, oldLayer: childLayer);
builder2.pop();
assert(() {
try {
builder2.addRetained(layer);
fail('Expected addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('The layer is already being used'));
}
return true;
}());
builder2.build();
}
// Attempts to retain a layer that has been used as `oldLayer` in a previous frame.
void testRetainOldLayer(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
pushFunction(builder2, layer);
builder2.pop();
assert(() {
try {
final SceneBuilder builder3 = SceneBuilder();
builder3.addRetained(layer);
fail('Expected addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('was previously used as oldLayer'));
}
return true;
}());
builder2.build();
}
// Attempts to pass layer as `oldLayer` that has been used as `oldLayer` in a previous frame.
void testPushOldLayer(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer layer = pushFunction(builder1, null);
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
pushFunction(builder2, layer);
builder2.pop();
assert(() {
try {
final SceneBuilder builder3 = SceneBuilder();
pushFunction(builder3, layer);
fail('Expected addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('was previously used as oldLayer'));
}
return true;
}());
builder2.build();
}
// Attempts to retain a parent of a layer used as `oldLayer` in a previous frame.
void testRetainsParentOfOldLayer(_TestNoSharingFunction pushFunction) {
final SceneBuilder builder1 = SceneBuilder();
final EngineLayer parentLayer = pushFunction(builder1, null);
final OpacityEngineLayer childLayer = builder1.pushOpacity(123);
builder1.pop();
builder1.pop();
builder1.build();
final SceneBuilder builder2 = SceneBuilder();
builder2.pushOpacity(321, oldLayer: childLayer);
builder2.pop();
assert(() {
try {
final SceneBuilder builder3 = SceneBuilder();
builder3.addRetained(parentLayer);
fail('Expected addRetained to throw AssertionError but it returned successully');
} on AssertionError catch (error) {
expect(error.toString(), contains('was previously used as oldLayer'));
}
return true;
}());
builder2.build();
}
void testNoSharing(_TestNoSharingFunction pushFunction) {
testPushThenIllegalRetain(pushFunction);
testAddRetainedThenIllegalPush(pushFunction);
testDoubleAddRetained(pushFunction);
testPushOldLayerTwice(pushFunction);
testPushChildLayerOfRetainedLayer(pushFunction);
testRetainParentLayerOfPushedChild(pushFunction);
testRetainOldLayer(pushFunction);
testPushOldLayer(pushFunction);
testRetainsParentOfOldLayer(pushFunction);
}
test('SceneBuilder does not share a layer between addRetained and push*', () {
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushOffset(0, 0, oldLayer: oldLayer as OffsetEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushTransform(Float64List(16), oldLayer: oldLayer as TransformEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushClipRect(Rect.zero, oldLayer: oldLayer as ClipRectEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushClipRRect(RRect.zero, oldLayer: oldLayer as ClipRRectEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushClipPath(Path(), oldLayer: oldLayer as ClipPathEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushOpacity(100, oldLayer: oldLayer as OpacityEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushBackdropFilter(ImageFilter.blur(), oldLayer: oldLayer as BackdropFilterEngineLayer?);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushShaderMask(
Gradient.radial(
Offset.zero,
10,
const <Color>[Color.fromARGB(0, 0, 0, 0), Color.fromARGB(0, 255, 255, 255)],
),
Rect.zero,
BlendMode.color,
oldLayer: oldLayer as ShaderMaskEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushColorFilter(
const ColorFilter.mode(
Color.fromARGB(0, 0, 0, 0),
BlendMode.color,
),
oldLayer: oldLayer as ColorFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushColorFilter(
const ColorFilter.matrix(<double>[
1, 0, 0, 0, 0,
0, 1, 0, 0, 0,
0, 0, 1, 0, 0,
0, 0, 0, 1, 0,
]),
oldLayer: oldLayer as ColorFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushColorFilter(
const ColorFilter.linearToSrgbGamma(),
oldLayer: oldLayer as ColorFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushColorFilter(
const ColorFilter.srgbToLinearGamma(),
oldLayer: oldLayer as ColorFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushImageFilter(
ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0),
oldLayer: oldLayer as ImageFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushImageFilter(
ImageFilter.dilate(radiusX: 10.0, radiusY: 10.0),
oldLayer: oldLayer as ImageFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushImageFilter(
ImageFilter.erode(radiusX: 10.0, radiusY: 10.0),
oldLayer: oldLayer as ImageFilterEngineLayer?,
);
});
testNoSharing((SceneBuilder builder, EngineLayer? oldLayer) {
return builder.pushImageFilter(
ImageFilter.matrix(Float64List.fromList(<double>[
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1,
])),
oldLayer: oldLayer as ImageFilterEngineLayer?,
);
});
});
}
typedef _TestNoSharingFunction = EngineLayer Function(SceneBuilder builder, EngineLayer? oldLayer);
| engine/testing/dart/compositing_test.dart/0 | {
"file_path": "engine/testing/dart/compositing_test.dart",
"repo_id": "engine",
"token_count": 5864
} | 431 |
// Copyright 2013 The Flutter 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 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
import 'canvas_test.dart' show createImage, testCanvas;
void main() {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
test('Construct an ImageShader', () async {
final Image image = await createImage(50, 50);
final ImageShader shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16));
final Paint paint = Paint()..shader = shader;
const Rect rect = Rect.fromLTRB(0, 0, 100, 100);
testCanvas((Canvas canvas) => canvas.drawRect(rect, paint));
if (assertsEnabled) {
expect(shader.debugDisposed, false);
}
shader.dispose();
if (assertsEnabled) {
expect(shader.debugDisposed, true);
}
image.dispose();
});
test('ImageShader with disposed image', () async {
final Image image = await createImage(50, 50);
image.dispose();
if (assertsEnabled) {
expectAssertion(() => ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16)));
} else {
throwsException(() => ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16)));
}
});
test('Disposed image shader in a paint', () async {
final Image image = await createImage(50, 50);
final ImageShader shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16));
shader.dispose();
if (assertsEnabled) {
expectAssertion(() => Paint()..shader = shader);
return;
}
final Paint paint = Paint()..shader = shader;
const Rect rect = Rect.fromLTRB(0, 0, 100, 100);
testCanvas((Canvas canvas) => canvas.drawRect(rect, paint));
image.dispose();
});
test('Construct an ImageShader - GPU image', () async {
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
canvas.drawPaint(Paint()..color = const Color(0xFFABCDEF));
final Picture picture = recorder.endRecording();
final Image image = picture.toImageSync(50, 50);
picture.dispose();
final ImageShader shader = ImageShader(image, TileMode.clamp, TileMode.clamp, Float64List(16));
final Paint paint = Paint()..shader=shader;
const Rect rect = Rect.fromLTRB(0, 0, 100, 100);
testCanvas((Canvas canvas) => canvas.drawRect(rect, paint));
if (assertsEnabled) {
expect(shader.debugDisposed, false);
}
shader.dispose();
if (assertsEnabled) {
expect(shader.debugDisposed, true);
}
image.dispose();
});
}
| engine/testing/dart/image_shader_test.dart/0 | {
"file_path": "engine/testing/dart/image_shader_test.dart",
"repo_id": "engine",
"token_count": 975
} | 432 |
// Copyright 2013 The Flutter 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 'dart:ui';
import 'package:litetest/litetest.dart';
void main() {
// Ahem font uses a constant ideographic/alphabetic baseline ratio.
const double kAhemBaselineRatio = 1.25;
test('predictably lays out a single-line paragraph - Ahem', () {
for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
));
builder.addText('Test');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 400.0));
expect(paragraph.height, closeTo(fontSize, 0.001));
expect(paragraph.width, closeTo(400.0, 0.001));
expect(paragraph.minIntrinsicWidth, closeTo(fontSize * 4.0, 0.001));
expect(paragraph.maxIntrinsicWidth, closeTo(fontSize * 4.0, 0.001));
expect(paragraph.alphabeticBaseline, closeTo(fontSize * .8, 0.001));
expect(
paragraph.ideographicBaseline,
closeTo(paragraph.alphabeticBaseline * kAhemBaselineRatio, 0.001),
);
}
});
test('predictably lays out a single-line paragraph - FlutterTest', () {
for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'FlutterTest',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
));
builder.addText('Test');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 400.0));
expect(paragraph.height, fontSize);
expect(paragraph.width, 400.0);
expect(paragraph.minIntrinsicWidth, fontSize * 4.0);
expect(paragraph.maxIntrinsicWidth, fontSize * 4.0);
expect(paragraph.alphabeticBaseline, fontSize * 0.75);
expect(paragraph.ideographicBaseline, fontSize);
}
});
test('predictably lays out a multi-line paragraph', () {
for (final double fontSize in <double>[10.0, 20.0, 30.0, 40.0]) {
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
));
builder.addText('Test Ahem');
final Paragraph paragraph = builder.build();
paragraph.layout(ParagraphConstraints(width: fontSize * 5.0));
expect(paragraph.height, closeTo(fontSize * 2.0, 0.001)); // because it wraps
expect(paragraph.width, closeTo(fontSize * 5.0, 0.001));
expect(paragraph.minIntrinsicWidth, closeTo(fontSize * 4.0, 0.001));
// TODO(yjbanov): see https://github.com/flutter/flutter/issues/21965
expect(paragraph.maxIntrinsicWidth, closeTo(fontSize * 9.0, 0.001));
expect(paragraph.alphabeticBaseline, closeTo(fontSize * .8, 0.001));
expect(
paragraph.ideographicBaseline,
closeTo(paragraph.alphabeticBaseline * kAhemBaselineRatio, 0.001),
);
}
});
test('getLineBoundary', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
));
builder.addText('Test Ahem');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: fontSize * 5.0));
// Wraps to two lines.
expect(paragraph.height, closeTo(fontSize * 2.0, 0.001));
const TextPosition wrapPositionDown = TextPosition(
offset: 5,
);
TextRange line = paragraph.getLineBoundary(wrapPositionDown);
expect(line.start, 5);
expect(line.end, 9);
const TextPosition wrapPositionUp = TextPosition(
offset: 5,
affinity: TextAffinity.upstream,
);
line = paragraph.getLineBoundary(wrapPositionUp);
expect(line.start, 0);
expect(line.end, 5);
const TextPosition wrapPositionStart = TextPosition(
offset: 0,
);
line = paragraph.getLineBoundary(wrapPositionStart);
expect(line.start, 0);
expect(line.end, 5);
const TextPosition wrapPositionEnd = TextPosition(
offset: 9,
);
line = paragraph.getLineBoundary(wrapPositionEnd);
expect(line.start, 5);
expect(line.end, 9);
});
test('getLineBoundary RTL', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
textDirection: TextDirection.rtl,
));
builder.addText('القاهرةالقاهرة');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: fontSize * 5.0));
// Wraps to three lines.
expect(paragraph.height, closeTo(fontSize * 3.0, 0.001));
const TextPosition wrapPositionDown = TextPosition(
offset: 5,
);
TextRange line = paragraph.getLineBoundary(wrapPositionDown);
expect(line.start, 5);
expect(line.end, 10);
const TextPosition wrapPositionUp = TextPosition(
offset: 5,
affinity: TextAffinity.upstream,
);
line = paragraph.getLineBoundary(wrapPositionUp);
expect(line.start, 0);
expect(line.end, 5);
const TextPosition wrapPositionStart = TextPosition(
offset: 0,
);
line = paragraph.getLineBoundary(wrapPositionStart);
expect(line.start, 0);
expect(line.end, 5);
const TextPosition wrapPositionEnd = TextPosition(
offset: 9,
);
line = paragraph.getLineBoundary(wrapPositionEnd);
expect(line.start, 5);
expect(line.end, 10);
});
test('getLineBoundary empty line', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'Ahem',
fontStyle: FontStyle.normal,
fontWeight: FontWeight.normal,
fontSize: fontSize,
textDirection: TextDirection.rtl,
));
builder.addText('Test\n\nAhem');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: fontSize * 5.0));
// Three lines due to line breaks, with the middle line being empty.
expect(paragraph.height, closeTo(fontSize * 3.0, 0.001));
const TextPosition emptyLinePosition = TextPosition(
offset: 5,
);
TextRange line = paragraph.getLineBoundary(emptyLinePosition);
expect(line.start, 5);
expect(line.end, 5);
// Since these are hard newlines, TextAffinity has no effect here.
const TextPosition emptyLinePositionUpstream = TextPosition(
offset: 5,
affinity: TextAffinity.upstream,
);
line = paragraph.getLineBoundary(emptyLinePositionUpstream);
expect(line.start, 5);
expect(line.end, 5);
const TextPosition endOfFirstLinePosition = TextPosition(
offset: 4,
);
line = paragraph.getLineBoundary(endOfFirstLinePosition);
expect(line.start, 0);
expect(line.end, 4);
const TextPosition startOfLastLinePosition = TextPosition(
offset: 6,
);
line = paragraph.getLineBoundary(startOfLastLinePosition);
expect(line.start, 6);
expect(line.end, 10);
});
test('getLineMetricsAt', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontSize: fontSize,
textDirection: TextDirection.rtl,
height: 2.0,
));
builder.addText('Test\npppp');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 100.0));
final LineMetrics? line = paragraph.getLineMetricsAt(1);
expect(line?.hardBreak, isTrue);
expect(line?.ascent, 15.0);
expect(line?.descent, 5.0);
expect(line?.height, 20.0);
expect(line?.width, 4 * 10.0);
expect(line?.left, 100.0 - 40.0);
expect(line?.baseline, 20.0 + 15.0);
expect(line?.lineNumber, 1);
});
test('line number', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(fontSize: fontSize));
builder.addText('Test\n\nTest');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 100.0));
expect(paragraph.numberOfLines, 3);
expect(paragraph.getLineNumberAt(4), 0); // first LF
expect(paragraph.getLineNumberAt(5), 1); // second LF
expect(paragraph.getLineNumberAt(6), 2); // "T" in the second "Test"
});
test('empty paragraph', () {
const double fontSize = 10.0;
final Paragraph paragraph = ParagraphBuilder(ParagraphStyle(
fontSize: fontSize,
)).build();
paragraph.layout(const ParagraphConstraints(width: double.infinity));
expect(paragraph.getClosestGlyphInfoForOffset(Offset.zero), isNull);
expect(paragraph.getGlyphInfoAt(0), isNull);
expect(paragraph.getLineMetricsAt(0), isNull);
expect(paragraph.numberOfLines, 0);
expect(paragraph.getLineNumberAt(0), isNull);
expect(paragraph.getGlyphInfoAt(0), isNull);
expect(paragraph.getClosestGlyphInfoForOffset(Offset.zero), isNull);
});
test('OOB indices as input', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontSize: fontSize,
maxLines: 1,
ellipsis: 'BBB',
))..addText('A' * 100);
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: 100));
expect(paragraph.numberOfLines, 1);
expect(paragraph.getLineMetricsAt(-1), isNull);
expect(paragraph.getLineMetricsAt(0)?.lineNumber, 0);
expect(paragraph.getLineMetricsAt(1), isNull);
expect(paragraph.getLineNumberAt(-1), isNull);
expect(paragraph.getLineNumberAt(0), 0);
expect(paragraph.getLineNumberAt(6), 0);
// The last 3 characters on the first line are ellipsized with BBB.
expect(paragraph.getLineMetricsAt(7), isNull);
expect(paragraph.getGlyphInfoAt(-1), isNull);
expect(paragraph.getGlyphInfoAt(0)?.graphemeClusterCodeUnitRange, const TextRange(start: 0, end: 1));
expect(paragraph.getGlyphInfoAt(6)?.graphemeClusterCodeUnitRange, const TextRange(start: 6, end: 7));
expect(paragraph.getGlyphInfoAt(7), isNull);
expect(paragraph.getGlyphInfoAt(200), isNull);
});
test('querying glyph info', () {
const double fontSize = 10.0;
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontSize: fontSize,
));
builder.addText('Test\nTest');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: double.infinity));
final GlyphInfo? bottomRight = paragraph.getClosestGlyphInfoForOffset(const Offset(99.0, 99.0));
final GlyphInfo? last = paragraph.getGlyphInfoAt(8);
expect(bottomRight, equals(last));
expect(bottomRight, notEquals(paragraph.getGlyphInfoAt(0)));
expect(bottomRight?.graphemeClusterLayoutBounds, const Rect.fromLTWH(30, 10, 10, 10));
expect(bottomRight?.graphemeClusterCodeUnitRange, const TextRange(start: 8, end: 9));
expect(bottomRight?.writingDirection, TextDirection.ltr);
});
test('painting a disposed paragraph does not crash', () {
final Paragraph paragraph = ParagraphBuilder(ParagraphStyle()).build();
paragraph.dispose();
final PictureRecorder recorder = PictureRecorder();
final Canvas canvas = Canvas(recorder);
void callback() { canvas.drawParagraph(paragraph, Offset.zero); }
if (assertStatementsEnabled) {
expectAssertion(callback);
} else {
expect(callback, throwsStateError);
}
});
test('rounding hack disabled', () {
const double fontSize = 1.25;
const String text = '12345';
assert((fontSize * text.length).truncate() != fontSize * text.length);
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(fontSize: fontSize));
builder.addText(text);
final Paragraph paragraph = builder.build()
..layout(const ParagraphConstraints(width: text.length * fontSize));
expect(paragraph.maxIntrinsicWidth, text.length * fontSize);
switch (paragraph.computeLineMetrics()) {
case [LineMetrics(width: final double width)]:
expect(width, text.length * fontSize);
case final List<LineMetrics> metrics:
expect(metrics, hasLength(1));
}
});
}
| engine/testing/dart/paragraph_test.dart/0 | {
"file_path": "engine/testing/dart/paragraph_test.dart",
"repo_id": "engine",
"token_count": 4641
} | 433 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This is testing some of the named constants.
// ignore_for_file: use_named_constants
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as path;
Future<Uint8List> readFile(String fileName) async {
final File file = File(path.join('flutter', 'testing', 'resources', fileName));
return file.readAsBytes();
}
void testFontWeight() {
test('FontWeight.lerp works with non-null values', () {
expect(FontWeight.lerp(FontWeight.w400, FontWeight.w600, .5), equals(FontWeight.w500));
});
test('FontWeight.lerp returns null if a and b are null', () {
expect(FontWeight.lerp(null, null, 0), isNull);
});
test('FontWeight.lerp returns FontWeight.w400 if a is null', () {
expect(FontWeight.lerp(null, FontWeight.w400, 0), equals(FontWeight.w400));
});
test('FontWeight.lerp returns FontWeight.w400 if b is null', () {
expect(FontWeight.lerp(FontWeight.w400, null, 1), equals(FontWeight.w400));
});
test('FontWeights have the correct value', () {
expect(FontWeight.w100.value, 100);
expect(FontWeight.w200.value, 200);
expect(FontWeight.w300.value, 300);
expect(FontWeight.w400.value, 400);
expect(FontWeight.w500.value, 500);
expect(FontWeight.w600.value, 600);
expect(FontWeight.w700.value, 700);
expect(FontWeight.w800.value, 800);
expect(FontWeight.w900.value, 900);
});
}
void testParagraphStyle() {
final ParagraphStyle ps0 = ParagraphStyle(textDirection: TextDirection.ltr, fontSize: 14.0);
final ParagraphStyle ps1 = ParagraphStyle(textDirection: TextDirection.rtl, fontSize: 14.0);
final ParagraphStyle ps2 = ParagraphStyle(textAlign: TextAlign.center, fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0);
final ParagraphStyle ps3 = ParagraphStyle(fontWeight: FontWeight.w700, fontSize: 12.0, height: 123.0);
test('ParagraphStyle toString works', () {
expect(ps0.toString(), equals('ParagraphStyle(textAlign: unspecified, textDirection: TextDirection.ltr, fontWeight: unspecified, fontStyle: unspecified, maxLines: unspecified, textHeightBehavior: unspecified, fontFamily: unspecified, fontSize: 14.0, height: unspecified, strutStyle: unspecified, ellipsis: unspecified, locale: unspecified)'));
expect(ps1.toString(), equals('ParagraphStyle(textAlign: unspecified, textDirection: TextDirection.rtl, fontWeight: unspecified, fontStyle: unspecified, maxLines: unspecified, textHeightBehavior: unspecified, fontFamily: unspecified, fontSize: 14.0, height: unspecified, strutStyle: unspecified, ellipsis: unspecified, locale: unspecified)'));
expect(ps2.toString(), equals('ParagraphStyle(textAlign: TextAlign.center, textDirection: unspecified, fontWeight: FontWeight.w800, fontStyle: unspecified, maxLines: unspecified, textHeightBehavior: unspecified, fontFamily: unspecified, fontSize: 10.0, height: 100.0x, strutStyle: unspecified, ellipsis: unspecified, locale: unspecified)'));
expect(ps3.toString(), equals('ParagraphStyle(textAlign: unspecified, textDirection: unspecified, fontWeight: FontWeight.w700, fontStyle: unspecified, maxLines: unspecified, textHeightBehavior: unspecified, fontFamily: unspecified, fontSize: 12.0, height: 123.0x, strutStyle: unspecified, ellipsis: unspecified, locale: unspecified)'));
});
}
void testTextStyle() {
final TextStyle ts0 = TextStyle(fontWeight: FontWeight.w700, fontSize: 12.0, height: 123.0);
final TextStyle ts1 = TextStyle(color: const Color(0xFF00FF00), fontWeight: FontWeight.w800, fontSize: 10.0, height: 100.0);
final TextStyle ts2 = TextStyle(fontFamily: 'test');
final TextStyle ts3 = TextStyle(fontFamily: 'foo', fontFamilyFallback: <String>['Roboto', 'test']);
final TextStyle ts4 = TextStyle(leadingDistribution: TextLeadingDistribution.even);
test('TextStyle toString works', () {
expect(
ts0.toString(),
equals('TextStyle(color: unspecified, decoration: unspecified, decorationColor: unspecified, decorationStyle: unspecified, decorationThickness: unspecified, fontWeight: FontWeight.w700, fontStyle: unspecified, textBaseline: unspecified, fontFamily: unspecified, fontFamilyFallback: unspecified, fontSize: 12.0, letterSpacing: unspecified, wordSpacing: unspecified, height: 123.0x, leadingDistribution: unspecified, locale: unspecified, background: unspecified, foreground: unspecified, shadows: unspecified, fontFeatures: unspecified, fontVariations: unspecified)'),
);
expect(
ts1.toString(),
equals('TextStyle(color: Color(0xff00ff00), decoration: unspecified, decorationColor: unspecified, decorationStyle: unspecified, decorationThickness: unspecified, fontWeight: FontWeight.w800, fontStyle: unspecified, textBaseline: unspecified, fontFamily: unspecified, fontFamilyFallback: unspecified, fontSize: 10.0, letterSpacing: unspecified, wordSpacing: unspecified, height: 100.0x, leadingDistribution: unspecified, locale: unspecified, background: unspecified, foreground: unspecified, shadows: unspecified, fontFeatures: unspecified, fontVariations: unspecified)'),
);
expect(
ts2.toString(),
equals('TextStyle(color: unspecified, decoration: unspecified, decorationColor: unspecified, decorationStyle: unspecified, decorationThickness: unspecified, fontWeight: unspecified, fontStyle: unspecified, textBaseline: unspecified, fontFamily: test, fontFamilyFallback: unspecified, fontSize: unspecified, letterSpacing: unspecified, wordSpacing: unspecified, height: unspecified, leadingDistribution: unspecified, locale: unspecified, background: unspecified, foreground: unspecified, shadows: unspecified, fontFeatures: unspecified, fontVariations: unspecified)'),
);
expect(
ts3.toString(),
equals('TextStyle(color: unspecified, decoration: unspecified, decorationColor: unspecified, decorationStyle: unspecified, decorationThickness: unspecified, fontWeight: unspecified, fontStyle: unspecified, textBaseline: unspecified, fontFamily: foo, fontFamilyFallback: [Roboto, test], fontSize: unspecified, letterSpacing: unspecified, wordSpacing: unspecified, height: unspecified, leadingDistribution: unspecified, locale: unspecified, background: unspecified, foreground: unspecified, shadows: unspecified, fontFeatures: unspecified, fontVariations: unspecified)'),
);
expect(
ts4.toString(),
equals('TextStyle(color: unspecified, decoration: unspecified, decorationColor: unspecified, decorationStyle: unspecified, decorationThickness: unspecified, fontWeight: unspecified, fontStyle: unspecified, textBaseline: unspecified, fontFamily: unspecified, fontFamilyFallback: unspecified, fontSize: unspecified, letterSpacing: unspecified, wordSpacing: unspecified, height: unspecified, leadingDistribution: TextLeadingDistribution.even, locale: unspecified, background: unspecified, foreground: unspecified, shadows: unspecified, fontFeatures: unspecified, fontVariations: unspecified)'),
);
});
}
void testTextHeightBehavior() {
const TextHeightBehavior behavior0 = TextHeightBehavior();
const TextHeightBehavior behavior1 = TextHeightBehavior(
applyHeightToFirstAscent: false,
applyHeightToLastDescent: false
);
const TextHeightBehavior behavior2 = TextHeightBehavior(
applyHeightToFirstAscent: false,
);
const TextHeightBehavior behavior3 = TextHeightBehavior(
applyHeightToLastDescent: false
);
const TextHeightBehavior behavior4 = TextHeightBehavior(
applyHeightToLastDescent: false,
leadingDistribution: TextLeadingDistribution.even,
);
test('TextHeightBehavior default constructor works', () {
expect(behavior0.applyHeightToFirstAscent, equals(true));
expect(behavior0.applyHeightToLastDescent, equals(true));
expect(behavior1.applyHeightToFirstAscent, equals(false));
expect(behavior1.applyHeightToLastDescent, equals(false));
expect(behavior2.applyHeightToFirstAscent, equals(false));
expect(behavior2.applyHeightToLastDescent, equals(true));
expect(behavior3.applyHeightToFirstAscent, equals(true));
expect(behavior3.applyHeightToLastDescent, equals(false));
expect(behavior4.applyHeightToLastDescent, equals(false));
expect(behavior4.leadingDistribution, equals(TextLeadingDistribution.even));
});
test('TextHeightBehavior toString works', () {
expect(behavior0.toString(), equals('TextHeightBehavior(applyHeightToFirstAscent: true, applyHeightToLastDescent: true, leadingDistribution: TextLeadingDistribution.proportional)'));
expect(behavior1.toString(), equals('TextHeightBehavior(applyHeightToFirstAscent: false, applyHeightToLastDescent: false, leadingDistribution: TextLeadingDistribution.proportional)'));
expect(behavior2.toString(), equals('TextHeightBehavior(applyHeightToFirstAscent: false, applyHeightToLastDescent: true, leadingDistribution: TextLeadingDistribution.proportional)'));
expect(behavior3.toString(), equals('TextHeightBehavior(applyHeightToFirstAscent: true, applyHeightToLastDescent: false, leadingDistribution: TextLeadingDistribution.proportional)'));
expect(behavior4.toString(), equals('TextHeightBehavior(applyHeightToFirstAscent: true, applyHeightToLastDescent: false, leadingDistribution: TextLeadingDistribution.even)'));
});
}
void testTextRange() {
test('TextRange empty ranges are correct', () {
const TextRange range = TextRange(start: -1, end: -1);
expect(range, equals(const TextRange.collapsed(-1)));
expect(range, equals(TextRange.empty));
});
test('TextRange isValid works', () {
expect(TextRange.empty.isValid, isFalse);
expect(const TextRange(start: 0, end: 0).isValid, isTrue);
expect(const TextRange(start: 0, end: 10).isValid, isTrue);
expect(const TextRange(start: 10, end: 10).isValid, isTrue);
expect(const TextRange(start: -1, end: 10).isValid, isFalse);
expect(const TextRange(start: 10, end: 0).isValid, isTrue);
expect(const TextRange(start: 10, end: -1).isValid, isFalse);
});
test('TextRange isCollapsed works', () {
expect(TextRange.empty.isCollapsed, isTrue);
expect(const TextRange(start: 0, end: 0).isCollapsed, isTrue);
expect(const TextRange(start: 0, end: 10).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: 10).isCollapsed, isTrue);
expect(const TextRange(start: -1, end: 10).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: 0).isCollapsed, isFalse);
expect(const TextRange(start: 10, end: -1).isCollapsed, isFalse);
});
test('TextRange isNormalized works', () {
expect(TextRange.empty.isNormalized, isTrue);
expect(const TextRange(start: 0, end: 0).isNormalized, isTrue);
expect(const TextRange(start: 0, end: 10).isNormalized, isTrue);
expect(const TextRange(start: 10, end: 10).isNormalized, isTrue);
expect(const TextRange(start: -1, end: 10).isNormalized, isTrue);
expect(const TextRange(start: 10, end: 0).isNormalized, isFalse);
expect(const TextRange(start: 10, end: -1).isNormalized, isFalse);
});
test('TextRange textBefore works', () {
expect(const TextRange(start: 0, end: 0).textBefore('hello'), isEmpty);
expect(const TextRange(start: 1, end: 1).textBefore('hello'), equals('h'));
expect(const TextRange(start: 1, end: 2).textBefore('hello'), equals('h'));
expect(const TextRange(start: 5, end: 5).textBefore('hello'), equals('hello'));
expect(const TextRange(start: 0, end: 5).textBefore('hello'), isEmpty);
});
test('TextRange textAfter works', () {
expect(const TextRange(start: 0, end: 0).textAfter('hello'), equals('hello'));
expect(const TextRange(start: 1, end: 1).textAfter('hello'), equals('ello'));
expect(const TextRange(start: 1, end: 2).textAfter('hello'), equals('llo'));
expect(const TextRange(start: 5, end: 5).textAfter('hello'), isEmpty);
expect(const TextRange(start: 0, end: 5).textAfter('hello'), isEmpty);
});
test('TextRange textInside works', () {
expect(const TextRange(start: 0, end: 0).textInside('hello'), isEmpty);
expect(const TextRange(start: 1, end: 1).textInside('hello'), isEmpty);
expect(const TextRange(start: 1, end: 2).textInside('hello'), equals('e'));
expect(const TextRange(start: 5, end: 5).textInside('hello'), isEmpty);
expect(const TextRange(start: 0, end: 5).textInside('hello'), equals('hello'));
});
}
void testGlyphInfo() {
test('constructor', () {
const Rect testRect = Rect.fromLTWH(1, 2, 3, 4);
const TextRange testRange = TextRange(start: 5, end: 6);
const TextDirection testDirection = TextDirection.ltr;
final GlyphInfo info = GlyphInfo(testRect, testRange, testDirection);
expect(info.graphemeClusterLayoutBounds, testRect);
expect(info.graphemeClusterCodeUnitRange, testRange);
expect(info.writingDirection, testDirection);
});
}
void testLoadFontFromList() {
test('loadFontFromList will send platform message after font is loaded', () async {
late String message;
channelBuffers.setListener(
'flutter/system',
(ByteData? data, PlatformMessageResponseCallback? callback) {
assert(data != null);
final Uint8List list = data!.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
message = utf8.decode(list);
},
);
final Uint8List fontData = Uint8List(0);
await loadFontFromList(fontData, fontFamily: 'fake');
expect(message, '{"type":"fontsChange"}');
channelBuffers.clearListener('flutter/system');
});
}
void testFontFeatureClass() {
test('FontFeature class', () {
expect(const FontFeature.alternative(1), const FontFeature('aalt'));
expect(const FontFeature.alternative(5), const FontFeature('aalt', 5));
expect(const FontFeature.alternativeFractions(), const FontFeature('afrc'));
expect(const FontFeature.contextualAlternates(), const FontFeature('calt'));
expect(const FontFeature.caseSensitiveForms(), const FontFeature('case'));
expect( FontFeature.characterVariant(1), const FontFeature('cv01'));
expect( FontFeature.characterVariant(18), const FontFeature('cv18'));
expect( FontFeature.characterVariant(99), const FontFeature('cv99'));
expect(const FontFeature.denominator(), const FontFeature('dnom'));
expect(const FontFeature.fractions(), const FontFeature('frac'));
expect(const FontFeature.historicalForms(), const FontFeature('hist'));
expect(const FontFeature.historicalLigatures(), const FontFeature('hlig'));
expect(const FontFeature.liningFigures(), const FontFeature('lnum'));
expect(const FontFeature.localeAware(), const FontFeature('locl'));
expect(const FontFeature.localeAware(), const FontFeature('locl'));
expect(const FontFeature.localeAware(enable: false), const FontFeature('locl', 0));
expect(const FontFeature.notationalForms(), const FontFeature('nalt'));
expect(const FontFeature.notationalForms(5), const FontFeature('nalt', 5));
expect(const FontFeature.numerators(), const FontFeature('numr'));
expect(const FontFeature.oldstyleFigures(), const FontFeature('onum'));
expect(const FontFeature.ordinalForms(), const FontFeature('ordn'));
expect(const FontFeature.proportionalFigures(), const FontFeature('pnum'));
expect(const FontFeature.randomize(), const FontFeature('rand'));
expect(const FontFeature.stylisticAlternates(), const FontFeature('salt'));
expect(const FontFeature.scientificInferiors(), const FontFeature('sinf'));
expect( FontFeature.stylisticSet(1), const FontFeature('ss01'));
expect( FontFeature.stylisticSet(18), const FontFeature('ss18'));
expect(const FontFeature.subscripts(), const FontFeature('subs'));
expect(const FontFeature.superscripts(), const FontFeature('sups'));
expect(const FontFeature.swash(), const FontFeature('swsh'));
expect(const FontFeature.swash(0), const FontFeature('swsh', 0));
expect(const FontFeature.swash(5), const FontFeature('swsh', 5));
expect(const FontFeature.tabularFigures(), const FontFeature('tnum'));
expect(const FontFeature.slashedZero(), const FontFeature('zero'));
expect(const FontFeature.enable('TEST'), const FontFeature('TEST'));
expect(const FontFeature.disable('TEST'), const FontFeature('TEST', 0));
expect(const FontFeature('FEAT', 1000).feature, 'FEAT');
expect(const FontFeature('FEAT', 1000).value, 1000);
expect(const FontFeature('FEAT', 1000).toString(), "FontFeature('FEAT', 1000)");
});
}
void testFontVariation() {
test('FontVariation', () async {
final Uint8List fontData = await readFile('RobotoSlab-VariableFont_wght.ttf');
await loadFontFromList(fontData, fontFamily: 'RobotoSerif');
final ParagraphBuilder baseBuilder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'RobotoSerif',
fontSize: 40.0,
));
baseBuilder.addText('Hello');
final Paragraph baseParagraph = baseBuilder.build();
baseParagraph.layout(const ParagraphConstraints(width: double.infinity));
final double baseWidth = baseParagraph.minIntrinsicWidth;
final ParagraphBuilder wideBuilder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'RobotoSerif',
fontSize: 40.0,
));
wideBuilder.pushStyle(TextStyle(
fontFamily: 'RobotoSerif',
fontSize: 40.0,
fontVariations: <FontVariation>[const FontVariation('wght', 900.0)],
));
wideBuilder.addText('Hello');
final Paragraph wideParagraph = wideBuilder.build();
wideParagraph.layout(const ParagraphConstraints(width: double.infinity));
final double wideWidth = wideParagraph.minIntrinsicWidth;
expect(wideWidth, greaterThan(baseWidth));
});
test('FontVariation constructors', () async {
expect(const FontVariation.weight(123.0).axis, 'wght');
expect(const FontVariation.weight(123.0).value, 123.0);
expect(const FontVariation.width(123.0).axis, 'wdth');
expect(const FontVariation.width(123.0).value, 123.0);
expect(const FontVariation.slant(45.0).axis, 'slnt');
expect(const FontVariation.slant(45.0).value, 45.0);
expect(const FontVariation.opticalSize(67.0).axis, 'opsz');
expect(const FontVariation.opticalSize(67.0).value, 67.0);
expect(const FontVariation.italic(0.8).axis, 'ital');
expect(const FontVariation.italic(0.8).value, 0.8);
});
test('FontVariation.lerp', () async {
expect(FontVariation.lerp(const FontVariation.weight(100.0), const FontVariation.weight(300.0), 0.5), const FontVariation.weight(200.0));
expect(FontVariation.lerp(const FontVariation.slant(0.0), const FontVariation.slant(-80.0), 0.25), const FontVariation.slant(-20.0));
expect(FontVariation.lerp(const FontVariation.width(90.0), const FontVariation.italic(0.2), 0.1), const FontVariation.width(90.0));
expect(FontVariation.lerp(const FontVariation.width(90.0), const FontVariation.italic(0.2), 0.9), const FontVariation.italic(0.2));
});
}
void testGetWordBoundary() {
test('GetWordBoundary', () async {
final Uint8List fontData = await readFile('RobotoSlab-VariableFont_wght.ttf');
await loadFontFromList(fontData, fontFamily: 'RobotoSerif');
final ParagraphBuilder builder = ParagraphBuilder(ParagraphStyle(
fontFamily: 'RobotoSerif',
fontSize: 40.0,
));
builder.addText('Hello team');
final Paragraph paragraph = builder.build();
paragraph.layout(const ParagraphConstraints(width: double.infinity));
TextRange range = paragraph.getWordBoundary(const TextPosition(offset: 5, affinity: TextAffinity.upstream));
expect(range.start, 0);
expect(range.end, 5);
range = paragraph.getWordBoundary(const TextPosition(offset: 5));
expect(range.start, 5);
expect(range.end, 6);
});
}
void main() {
testFontWeight();
testParagraphStyle();
testTextStyle();
testTextHeightBehavior();
testTextRange();
testGlyphInfo();
testLoadFontFromList();
testFontFeatureClass();
testFontVariation();
testGetWordBoundary();
}
| engine/testing/dart/text_test.dart/0 | {
"file_path": "engine/testing/dart/text_test.dart",
"repo_id": "engine",
"token_count": 6408
} | 434 |
#!/usr/bin/env vpython3
# [VPYTHON:BEGIN]
# python_version: "3.8"
# wheel <
# name: "infra/python/wheels/pyyaml/${platform}_${py_python}_${py_abi}"
# version: "version:5.4.1.chromium.1"
# >
# [VPYTHON:END]
# Copyright 2013 The Flutter 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 os
import shutil
import unittest
from pathlib import Path
# pylint is looking for a wrong //testing/run_tests.py.
# pylint: disable=no-member
import run_tests
run_tests.OUT_DIR = '/tmp/out/fuchsia_debug_x64'
os.makedirs(run_tests.OUT_DIR, exist_ok=True)
class RunTestsTest(unittest.TestCase):
def test_resolve_both_package_and_packages(self):
packages = run_tests.resolve_packages([{'package': 'abc'}, {'packages': ['abc', 'def']}])
self.assertEqual(
packages, {os.path.join(run_tests.OUT_DIR, 'abc'),
os.path.join(run_tests.OUT_DIR, 'def')}
)
def test_resolve_package_make_symbolic_link(self):
Path(os.path.join(run_tests.OUT_DIR, 'abc-0.far')).touch()
packages = run_tests.resolve_packages([
{'package': 'abc-0.far'},
])
self.assertEqual(packages, {os.path.join(run_tests.OUT_DIR, 'abc.far')})
self.assertTrue(os.path.islink(os.path.join(run_tests.OUT_DIR, 'abc.far')))
def test_build_test_cases_with_arguments(self):
test_cases = run_tests.build_test_cases([
{'test_command': 'test run abc'},
{'test_command': 'test run def -- --args'},
])
self.assertEqual(
test_cases,
[run_tests.TestCase(package='abc'),
run_tests.TestCase(package='def', args='--args')]
)
if __name__ == '__main__':
try:
unittest.main()
finally:
# Clean up the temporary files. Since it's in /tmp/, ignore the errors.
shutil.rmtree(run_tests.OUT_DIR, ignore_errors=True)
| engine/testing/fuchsia/run_tests_test.py/0 | {
"file_path": "engine/testing/fuchsia/run_tests_test.py",
"repo_id": "engine",
"token_count": 790
} | 435 |
// Copyright 2013 The Flutter 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 'package:async_helper/async_minitest.dart';
import 'package:expect/expect.dart';
/// The epsilon of tolerable double precision error.
///
/// This is used in various places in the framework to allow for floating point
/// precision loss in calculations. Differences below this threshold are safe
/// to disregard.
const double precisionErrorTolerance = 1e-10;
/// Asserts that `callback` throws an [AssertionError].
///
/// When running in a VM in which assertions are enabled, asserts that the
/// specified callback throws an [AssertionError]. When asserts are not
/// enabled, such as when running using a release-mode VM with default
/// settings, this acts as a no-op.
void expectAssertion(dynamic callback) {
bool assertsEnabled = false;
assert(() {
assertsEnabled = true;
return true;
}());
if (assertsEnabled) {
throwsA(isInstanceOf<AssertionError>())(callback);
}
}
/// Asserts that `callback` throws an [ArgumentError].
void expectArgumentError(dynamic callback) {
throwsA(isInstanceOf<ArgumentError>())(callback);
}
/// Asserts that `callback` throws some [Exception].
void throwsException(dynamic callback) {
throwsA(isInstanceOf<Exception>())(callback);
}
/// A [Matcher] that matches empty [String]s and [Iterable]s.
void isEmpty(dynamic d) {
if (d is String) {
expect(d.isEmpty, true);
return;
}
expect(d, isInstanceOf<Iterable<dynamic>>());
Expect.isEmpty(d as Iterable<dynamic>);
}
/// A [Matcher] that matches non-empty [String]s and [Iterable]s.
void isNotEmpty(dynamic d) {
if (d is String) {
expect(d.isNotEmpty, true);
return;
}
expect(d, isInstanceOf<Iterable<dynamic>>());
Expect.isNotEmpty(d as Iterable<dynamic>);
}
/// Gives a [Matcher] that asserts that the value being matched is within
/// `tolerance` of `value`.
Matcher closeTo(num value, num tolerance) => (dynamic actual) {
Expect.approxEquals(value, actual as num, tolerance);
};
/// A [Matcher] that matches NaN.
void isNaN(dynamic v) {
expect(v, isInstanceOf<num>());
expect(double.nan.compareTo(v as num) == 0, true);
}
/// Gives a [Matcher] that asserts that the value being matched is not equal to
/// `unexpected`.
Matcher notEquals(dynamic unexpected) => (dynamic actual) {
Expect.notEquals(unexpected, actual);
};
/// A [Matcher] that matches non-zero values.
void isNonZero(dynamic d) {
Expect.notEquals(0, d);
}
/// A [Matcher] that matches functions that throw a [RangeError] when invoked.
void throwsRangeError(dynamic d) {
Expect.throwsRangeError(d as void Function());
}
/// Gives a [Matcher] that asserts that the value being matched is a [String]
/// that contains `s` as a substring.
Matcher contains(String s) => (dynamic d) {
expect(d, isInstanceOf<String>());
Expect.contains(s, d as String);
};
/// Gives a [Matcher] that asserts that the value being matched is an [Iterable]
/// of length `d`.
Matcher hasLength(int l) => (dynamic d) {
expect(d, isInstanceOf<Iterable<dynamic>>());
expect((d as Iterable<dynamic>).length, equals(l));
};
/// Gives a matcher that asserts that the value being matched is a [String] that
/// starts with `s`.
Matcher startsWith(String s) => (dynamic d) {
expect(d, isInstanceOf<String>());
final String h = d as String;
if (!h.startsWith(s)) {
Expect.fail('Expected "$h" to start with "$s"');
}
};
/// Gives a matcher that asserts that the value being matched is a [String] that
/// ends with `s`.
Matcher endsWith(String s) => (dynamic d) {
expect(d, isInstanceOf<String>());
final String h = d as String;
if (!h.endsWith(s)) {
Expect.fail('Expected "$h" to end with "$s"');
}
};
/// Gives a matcher that asserts that the value being matched is a [String] that
/// regexp matches with `pattern`.
Matcher hasMatch(String pattern) => (dynamic d) {
expect(d, isInstanceOf<String>());
final String h = d as String;
final RegExp regExp = RegExp(pattern);
if (!regExp.hasMatch(h)) {
Expect.fail('Expected "$h" to match with "$pattern"');
}
};
/// Gives a matcher that asserts that the value being matched is a
/// `List<String>` that contains the entries in `pattern` in order.
/// There may be values that are not in the pattern interleaved.
Matcher containsStringsInOrder(List<String> pattern) => (dynamic d) {
expect(d, isInstanceOf<List<String>>());
final List<String> input = d as List<String>;
int cursor = 0;
for (final String el in input) {
if (cursor == pattern.length) {
break;
}
if (el == pattern[cursor]) {
cursor++;
}
}
if (cursor < pattern.length) {
Expect.fail('Did not find ${pattern[cursor]} in $d');
}
};
/// Gives a matcher that asserts that the value being matched is a
/// `List<String>` that does not contain any of the values in `unexpected`.
Matcher doesNotContainAny(List<String> unexpected) => (dynamic d) {
expect(d, isInstanceOf<List<String>>());
final List<String> input = d as List<String>;
for (final String string in input) {
if (unexpected.contains(string)) {
Expect.fail("String '$d' is unexpected");
}
}
};
| engine/testing/litetest/lib/src/matchers.dart/0 | {
"file_path": "engine/testing/litetest/lib/src/matchers.dart",
"repo_id": "engine",
"token_count": 1918
} | 436 |
# Copyright 2013 The Flutter 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("//flutter/build/dart/rules.gni")
import("//flutter/testing/rules/runtime_mode.gni")
flutter_snapshot("scenario_app_snapshot") {
main_dart = "lib/main.dart"
package_config = ".dart_tool/package_config.json"
}
if (!is_aot) {
if (is_android) {
_flutter_assets_dir = "$root_out_dir/scenario_app/app/assets/flutter_assets"
} else if (is_ios) {
_flutter_assets_dir =
"$root_out_dir/scenario_app/Scenarios/App.framework/flutter_assets"
} else {
assert(false)
}
copy("copy_jit_assets") {
visibility = [ ":*" ]
sources = [
"$target_gen_dir/isolate_snapshot_data",
"$target_gen_dir/isolate_snapshot_instr",
"$target_gen_dir/kernel_blob.bin",
]
outputs = [ "$_flutter_assets_dir/{{source_file_part}}" ]
deps = [ ":scenario_app_snapshot" ]
}
}
group("scenario_app") {
deps = [ ":scenario_app_snapshot" ]
if (!is_aot) {
deps += [ ":copy_jit_assets" ]
}
if (is_android) {
deps += [ "android" ]
}
if (is_ios) {
deps += [ "ios" ]
}
}
| engine/testing/scenario_app/BUILD.gn/0 | {
"file_path": "engine/testing/scenario_app/BUILD.gn",
"repo_id": "engine",
"token_count": 507
} | 437 |
// Copyright 2013 The Flutter 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 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dir_contents_diff/dir_contents_diff.dart' show dirContentsDiff;
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart';
import 'package:process/process.dart';
import 'package:skia_gold_client/skia_gold_client.dart';
import 'utils/adb_logcat_filtering.dart';
import 'utils/environment.dart';
import 'utils/logs.dart';
import 'utils/options.dart';
import 'utils/process_manager_extension.dart';
import 'utils/screenshot_transformer.dart';
// If you update the arguments, update the documentation in the README.md file.
void main(List<String> args) async {
// Get some basic environment information to guide the rest of the program.
final Environment environment = Environment(
isCi: Platform.environment['LUCI_CONTEXT'] != null,
showVerbose: Options.showVerbose(args),
logsDir: Platform.environment['FLUTTER_LOGS_DIR'],
);
// Determine if the CWD is within an engine checkout.
final Engine? localEngineDir = Engine.tryFindWithin();
// Show usage if requested.
if (Options.showUsage(args)) {
stdout.writeln(Options.usage(
environment: environment,
localEngineDir: localEngineDir,
));
return;
}
// Parse the command line arguments.
final Options options;
try {
options = Options.parse(
args,
environment: environment,
localEngine: localEngineDir,
);
} on FormatException catch (error) {
stderr.writeln(error);
stderr.writeln(Options.usage(
environment: environment,
localEngineDir: localEngineDir,
));
exitCode = 1;
return;
}
// Capture CTRL-C.
late final StreamSubscription<void> onSigint;
runZonedGuarded(
() async {
onSigint = ProcessSignal.sigint.watch().listen((_) {
onSigint.cancel();
panic(<String>['Received SIGINT']);
});
await _run(
verbose: options.verbose,
outDir: Directory(options.outDir),
adb: File(options.adb),
smokeTestFullPath: options.smokeTest,
useSkiaGold: options.useSkiaGold,
enableImpeller: options.enableImpeller,
impellerBackend: _ImpellerBackend.tryParse(options.impellerBackend),
logsDir: Directory(options.logsDir),
contentsGolden: options.outputContentsGolden,
ndkStack: options.ndkStack,
forceSurfaceProducerSurfaceTexture: options.forceSurfaceProducerSurfaceTexture,
prefixLogsPerRun: options.prefixLogsPerRun,
);
onSigint.cancel();
exit(0);
},
(Object error, StackTrace stackTrace) {
onSigint.cancel();
if (error is! Panic) {
stderr.writeln('Unhandled error: $error');
stderr.writeln(stackTrace);
}
exitCode = 1;
},
);
}
const int _tcpPort = 3001;
enum _ImpellerBackend {
vulkan,
opengles;
static _ImpellerBackend? tryParse(String? value) {
for (final _ImpellerBackend backend in _ImpellerBackend.values) {
if (backend.name == value) {
return backend;
}
}
return null;
}
}
Future<void> _run({
required bool verbose,
required Directory outDir,
required File adb,
required String? smokeTestFullPath,
required bool useSkiaGold,
required bool enableImpeller,
required _ImpellerBackend? impellerBackend,
required Directory logsDir,
required String? contentsGolden,
required String ndkStack,
required bool forceSurfaceProducerSurfaceTexture,
required bool prefixLogsPerRun,
}) async {
const ProcessManager pm = LocalProcessManager();
final String scenarioAppPath = join(outDir.path, 'scenario_app');
// Due to the CI environment, the logs directory persists between runs and
// even different builds. Because we're checking the output directory after
// each run, we need a clean logs directory to avoid false positives.
//
// Only after the runner is done, we can move the logs to the final location.
//
// See [_copyFiles] below and https://github.com/flutter/flutter/issues/144402.
final Directory finalLogsDir = logsDir..createSync(recursive: true);
logsDir = Directory.systemTemp.createTempSync('scenario_app_test_logs.');
final String logcatPath = join(logsDir.path, 'logcat.txt');
final String screenshotPath = logsDir.path;
final String apkOutPath = join(scenarioAppPath, 'app', 'outputs', 'apk');
final File testApk = File(join(apkOutPath, 'androidTest', 'debug', 'app-debug-androidTest.apk'));
final File appApk = File(join(apkOutPath, 'debug', 'app-debug.apk'));
log('writing logs and screenshots to ${logsDir.path}');
if (!testApk.existsSync()) {
panic(<String>[
'test apk does not exist: ${testApk.path}',
'make sure to build the selected engine variant'
]);
}
if (!appApk.existsSync()) {
panic(<String>[
'app apk does not exist: ${appApk.path}',
'make sure to build the selected engine variant'
]);
}
// Start a TCP socket in the host, and forward it to the device that runs the tests.
// This allows the test process to start a connection with the host, and write the bytes
// for the screenshots.
// On LUCI, the host uploads the screenshots to Skia Gold.
SkiaGoldClient? skiaGoldClient;
late final ServerSocket server;
final List<Future<void>> pendingComparisons = <Future<void>>[];
final List<Socket> pendingConnections = <Socket>[];
int comparisonsFailed = 0;
await step('Starting server...', () async {
server = await ServerSocket.bind(InternetAddress.anyIPv4, _tcpPort);
if (verbose) {
stdout.writeln('listening on host ${server.address.address}:${server.port}');
}
server.listen((Socket client) {
if (verbose) {
stdout.writeln('client connected ${client.remoteAddress.address}:${client.remotePort}');
}
pendingConnections.add(client);
client.transform(const ScreenshotBlobTransformer()).listen((Screenshot screenshot) {
final String fileName = screenshot.filename;
final Uint8List fileContent = screenshot.fileContent;
if (verbose) {
log('host received ${fileContent.lengthInBytes} bytes for screenshot `$fileName`');
}
assert(skiaGoldClient != null, 'expected Skia Gold client');
late File goldenFile;
try {
goldenFile = File(join(screenshotPath, fileName))..writeAsBytesSync(fileContent, flush: true);
} on FileSystemException catch (err) {
panic(<String>['failed to create screenshot $fileName: $err']);
}
if (verbose) {
log('wrote ${goldenFile.absolute.path}');
}
if (SkiaGoldClient.isAvailable()) {
final Future<void> comparison = skiaGoldClient!
.addImg(
fileName,
goldenFile,
screenshotSize: screenshot.pixelCount,
// Each color channel can be off by 2.
pixelColorDelta: 8,
)
.then((_) => logImportant('skia gold comparison succeeded: $fileName'))
.catchError((Object error) {
logWarning('skia gold comparison failed: $error');
comparisonsFailed++;
});
pendingComparisons.add(comparison);
}
}, onDone: () {
pendingConnections.remove(client);
});
});
});
late Process logcatProcess;
late Future<int> logcatProcessExitCode;
_ImpellerBackend? actualImpellerBackend;
final IOSink logcat = File(logcatPath).openWrite();
try {
await step('Creating screenshot directory `$screenshotPath`...', () async {
Directory(screenshotPath).createSync(recursive: true);
});
await step('Starting logcat...', () async {
final int exitCode = await pm.runAndForward(<String>[adb.path, 'logcat', '-c']);
if (exitCode != 0) {
panic(<String>['could not clear logs']);
}
logcatProcess = await pm.start(<String>[adb.path, 'logcat', '-T', '1']);
final (Future<int> logcatExitCode, Stream<String> logcatOutput) = getProcessStreams(logcatProcess);
logcatProcessExitCode = logcatExitCode;
String? filterProcessId;
logcatOutput.listen((String line) {
// Always write to the full log.
logcat.writeln(line);
if (enableImpeller && actualImpellerBackend == null && line.contains('Using the Impeller rendering backend')) {
if (line.contains('OpenGLES')) {
actualImpellerBackend = _ImpellerBackend.opengles;
} else if (line.contains('Vulkan')) {
actualImpellerBackend = _ImpellerBackend.vulkan;
} else {
panic(<String>[
'Impeller was enabled, but $line did not contain "OpenGLES" or "Vulkan".',
]);
}
}
// Conditionally parse and write to stderr.
final AdbLogLine? adbLogLine = AdbLogLine.tryParse(line);
if (verbose || adbLogLine == null) {
log(line);
return;
}
// If we haven't already found a process ID, try to find one.
// The process ID will help us filter out logs from other processes.
filterProcessId ??= adbLogLine.tryParseProcess();
// If this is a "verbose" log, possibly skip it.
final bool isVerbose = adbLogLine.isVerbose(filterProcessId: filterProcessId);
if (isVerbose || filterProcessId == null) {
// We've requested verbose output, so print everything.
if (verbose) {
adbLogLine.printFormatted();
}
return;
}
// It's a non-verbose log, so print it.
adbLogLine.printFormatted();
}, onError: (Object? err) {
if (verbose) {
logWarning('logcat stream error: $err');
}
});
});
await step('Configuring emulator...', () async {
final int exitCode = await pm.runAndForward(<String>[
adb.path,
'shell',
'settings',
'put',
'secure',
'immersive_mode_confirmations',
'confirmed',
]);
if (exitCode != 0) {
panic(<String>['could not configure emulator']);
}
});
await step('Get API level of connected device...', () async {
final ProcessResult apiLevelProcessResult = await pm.run(<String>[adb.path, 'shell', 'getprop', 'ro.build.version.sdk']);
if (apiLevelProcessResult.exitCode != 0) {
panic(<String>['could not get API level of the connected device']);
}
final String connectedDeviceAPILevel = (apiLevelProcessResult.stdout as String).trim();
final Map<String, String> dimensions = <String, String>{
'AndroidAPILevel': connectedDeviceAPILevel,
'GraphicsBackend': enableImpeller ? 'impeller-${impellerBackend!.name}' : 'skia',
'ForceSurfaceProducerSurfaceTexture': '$forceSurfaceProducerSurfaceTexture'
};
log('using dimensions: ${json.encode(dimensions)}');
skiaGoldClient = SkiaGoldClient(
outDir,
dimensions: dimensions,
);
});
await step('Skia Gold auth...', () async {
if (SkiaGoldClient.isAvailable()) {
await skiaGoldClient!.auth();
log('skia gold client is available');
} else {
if (useSkiaGold) {
panic(<String>['skia gold client is unavailable']);
} else {
log('skia gold client is unavaialble');
}
}
});
await step('Reverse port...', () async {
final int exitCode = await pm.runAndForward(<String>[adb.path, 'reverse', 'tcp:3000', 'tcp:$_tcpPort']);
if (exitCode != 0) {
panic(<String>['could not forward port']);
}
});
await step('Installing app APK...', () async {
final int exitCode = await pm.runAndForward(<String>[adb.path, 'install', appApk.path]);
if (exitCode != 0) {
panic(<String>['could not install app apk']);
}
});
await step('Installing test APK...', () async {
final int exitCode = await pm.runAndForward(<String>[adb.path, 'install', testApk.path]);
if (exitCode != 0) {
panic(<String>['could not install test apk']);
}
});
await step('Running instrumented tests...', () async {
final (int exitCode, StringBuffer out) = await pm.runAndCapture(<String>[
adb.path,
'shell',
'am',
'instrument',
'-w',
'--no-window-animation',
if (smokeTestFullPath != null)
'-e class $smokeTestFullPath',
if (enableImpeller)
'-e enable-impeller true',
if (impellerBackend != null)
'-e impeller-backend ${impellerBackend.name}',
if (forceSurfaceProducerSurfaceTexture)
'-e force-surface-producer-surface-texture true',
'dev.flutter.scenarios.test/dev.flutter.TestRunner',
]);
if (exitCode != 0) {
panic(<String>['instrumented tests failed to run']);
}
// Unfortunately adb shell am instrument does not return a non-zero exit
// code when tests fail, but it does seem to print "FAILURES!!!" to
// stdout, so we can use that as a signal that something went wrong.
if (out.toString().contains('FAILURES!!!')) {
stdout.write(out);
panic(<String>['1 or more tests failed']);
} else if (comparisonsFailed > 0) {
panic(<String>['$comparisonsFailed Skia Gold comparisons failed']);
}
});
} finally {
await server.close();
for (final Socket client in pendingConnections.toList()) {
client.close();
}
await step('Killing test app and test runner...', () async {
final int exitCode = await pm.runAndForward(<String>[adb.path, 'shell', 'am', 'force-stop', 'dev.flutter.scenarios']);
if (exitCode != 0) {
panic(<String>['could not kill test app']);
}
});
await step('Killing logcat process...', () async {
final bool delivered = logcatProcess.kill(ProcessSignal.sigkill);
assert(delivered);
await logcatProcessExitCode;
});
await step('Flush logcat...', () async {
await logcat.flush();
await logcat.close();
log('wrote logcat to $logcatPath');
// Copy the logs to the final location.
// Optionally prefix the logs with a run number and backend name.
// See https://github.com/flutter/flutter/issues/144402.
final StringBuffer prefix = StringBuffer();
if (prefixLogsPerRun) {
final int rerunNumber = _getAndIncrementRerunNumber(finalLogsDir.path);
prefix.write('run_$rerunNumber.');
if (enableImpeller) {
prefix.write('impeller');
} else {
prefix.write('skia');
}
if (enableImpeller) {
prefix.write('_${impellerBackend!.name}');
}
if (forceSurfaceProducerSurfaceTexture) {
prefix.write('_force-st');
}
prefix.write('.');
}
_copyFiles(
source: logsDir,
destination: finalLogsDir,
prefix: prefix.toString(),
);
});
if (enableImpeller) {
await step('Validating Impeller...', () async {
final _ImpellerBackend expectedImpellerBackend = impellerBackend ?? _ImpellerBackend.vulkan;
if (actualImpellerBackend != expectedImpellerBackend) {
panic(<String>[
'--enable-impeller was specified and expected to find "${expectedImpellerBackend.name}", which did not match "${actualImpellerBackend?.name ?? '<impeller disabled>'}".',
]);
}
});
}
await step('Symbolize stack traces', () async {
final ProcessResult result = await pm.run(
<String>[
ndkStack,
'-sym',
outDir.path,
'-dump',
logcatPath,
],
);
if (result.exitCode != 0) {
panic(<String>['Failed to symbolize stack traces']);
}
});
await step('Remove reverse port...', () async {
final int exitCode = await pm.runAndForward(<String>[
adb.path,
'reverse',
'--remove',
'tcp:3000',
]);
if (exitCode != 0) {
panic(<String>['could not unforward port']);
}
});
await step('Uninstalling app APK...', () async {
final int exitCode = await pm.runAndForward(
<String>[adb.path, 'uninstall', 'dev.flutter.scenarios']);
if (exitCode != 0) {
panic(<String>['could not uninstall app apk']);
}
});
await step('Uninstalling test APK...', () async {
final int exitCode = await pm.runAndForward(
<String>[adb.path, 'uninstall', 'dev.flutter.scenarios.test']);
if (exitCode != 0) {
panic(<String>['could not uninstall app apk']);
}
});
await step('Wait for Skia gold comparisons...', () async {
await Future.wait(pendingComparisons);
});
final bool allTestsRun = smokeTestFullPath == null;
final bool checkGoldens = contentsGolden != null;
if (allTestsRun && checkGoldens) {
// Check the output here.
await step('Check output files...', () async {
// TODO(matanlurey): Resolve this in a better way. On CI this file always exists.
File(join(screenshotPath, 'noop.txt')).writeAsStringSync('');
// TODO(gaaclarke): We should move this into dir_contents_diff.
final String diffScreenhotPath = absolute(screenshotPath);
_withTemporaryCwd(absolute(dirname(contentsGolden)), () {
final int exitCode = dirContentsDiff(basename(contentsGolden), diffScreenhotPath);
if (exitCode != 0) {
panic(<String>['Output contents incorrect.']);
}
});
});
}
}
}
void _withTemporaryCwd(String path, void Function() callback) {
final String originalCwd = Directory.current.path;
Directory.current = Directory(path).path;
try {
callback();
} finally {
Directory.current = originalCwd;
}
}
/// Reads the file named `reruns.txt` in the logs directory and returns the number of reruns.
///
/// If the file does not exist, it is created with the number 1 and that number is returned.
int _getAndIncrementRerunNumber(String logsDir) {
final File rerunFile = File(join(logsDir, 'reruns.txt'));
if (!rerunFile.existsSync()) {
rerunFile.writeAsStringSync('1');
return 1;
}
final int rerunNumber = int.parse(rerunFile.readAsStringSync()) + 1;
rerunFile.writeAsStringSync(rerunNumber.toString());
return rerunNumber;
}
/// Copies the contents of [source] to [destination], optionally adding a [prefix] to the destination path.
///
/// This function is used to copy the screenshots from the device to the logs directory.
void _copyFiles({
required Directory source,
required Directory destination,
String prefix = '',
}) {
for (final FileSystemEntity entity in source.listSync()) {
if (entity is File) {
entity.copySync(join(destination.path, prefix + basename(entity.path)));
}
}
}
| engine/testing/scenario_app/bin/run_android_tests.dart/0 | {
"file_path": "engine/testing/scenario_app/bin/run_android_tests.dart",
"repo_id": "engine",
"token_count": 7583
} | 438 |
// Copyright 2020 The Flutter 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 <XCTest/XCTest.h>
#import "GoldenTestManager.h"
@interface AppExtensionTests : XCTestCase
@property(nonatomic, strong) XCUIApplication* hostApplication;
@end
@implementation AppExtensionTests
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
self.hostApplication =
[[XCUIApplication alloc] initWithBundleIdentifier:@"dev.flutter.FlutterAppExtensionTestHost"];
}
- (void)testAppExtensionLaunching {
// Launch the Scenarios app first to ensure it's installed then close it.
XCUIApplication* app = [[XCUIApplication alloc] init];
[app launch];
[app terminate];
[self.hostApplication launch];
XCUIElement* button = self.hostApplication.buttons[@"Open Share"];
if (![button waitForExistenceWithTimeout:10]) {
NSLog(@"%@", self.hostApplication.debugDescription);
XCTFail(@"Failed due to not able to find any button with %@ seconds", @(10));
}
[button tap];
BOOL launchedExtensionInFlutter = NO;
// Wait for first cell of share sheet to appear.
XCUIElement* firstCell = self.hostApplication.collectionViews.cells.firstMatch;
if (![firstCell waitForExistenceWithTimeout:10]) {
NSLog(@"%@", self.hostApplication.debugDescription);
XCTFail(@"Failed due to not able to find any cells with %@ seconds", @(10));
}
// Custom share extension button (like the one in this test) does not have a
// unique identity on older versions of iOS. They are all identified as
// `XCElementSnapshotPrivilegedValuePlaceholder`. On iOS 17, they are
// identified by name. Loop through all the buttons labeled
// `XCElementSnapshotPrivilegedValuePlaceholder` or `Scenarios` to find the
// Flutter one.
NSPredicate* cellPredicate = [NSPredicate
predicateWithFormat:
@"label == 'XCElementSnapshotPrivilegedValuePlaceholder' OR label = 'Scenarios'"];
NSArray<XCUIElement*>* shareSheetCells =
[self.hostApplication.collectionViews.cells matchingPredicate:cellPredicate]
.allElementsBoundByIndex;
for (XCUIElement* shareSheetCell in shareSheetCells) {
[shareSheetCell tap];
XCUIElement* flutterView = self.hostApplication.otherElements[@"flutter_view"];
if ([flutterView waitForExistenceWithTimeout:10]) {
launchedExtensionInFlutter = YES;
break;
}
// All the built-in share extensions have a Cancel button.
// Tap the Cancel button to close the built-in extension.
XCUIElement* cancel = self.hostApplication.buttons[@"Cancel"];
if ([cancel waitForExistenceWithTimeout:10]) {
[cancel tap];
}
}
// App extension successfully launched flutter view.
XCTAssertTrue(launchedExtensionInFlutter);
}
@end
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/AppExtensionTests.m/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/AppExtensionTests.m",
"repo_id": "engine",
"token_count": 935
} | 439 |
// Copyright 2020 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_STATUSBARTEST_H_
#define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_STATUSBARTEST_H_
#import <XCTest/XCTest.h>
NS_ASSUME_NONNULL_BEGIN
@interface StatusBarTest : XCTestCase
@property(nonatomic, strong) XCUIApplication* application;
@end
NS_ASSUME_NONNULL_END
#endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSUITESTS_STATUSBARTEST_H_
| engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/StatusBarTest.h/0 | {
"file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/StatusBarTest.h",
"repo_id": "engine",
"token_count": 245
} | 440 |
// Copyright 2013 The Flutter 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 'dart:async';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'src/scenarios.dart';
void main() {
// TODO(goderbauer): Create a window if embedder doesn't provide an implicit
// view to draw into once we have a windowing API and set the window's
// FlutterView to the _view property.
assert(PlatformDispatcher.instance.implicitView != null);
PlatformDispatcher.instance
..onBeginFrame = _onBeginFrame
..onDrawFrame = _onDrawFrame
..onMetricsChanged = _onMetricsChanged
..onPointerDataPacket = _onPointerDataPacket
..scheduleFrame();
channelBuffers.setListener('driver', _handleDriverMessage);
channelBuffers.setListener('write_timeline', _handleWriteTimelineMessage);
final FlutterView view = PlatformDispatcher.instance.implicitView!;
// Asserting that this is greater than zero since this app runs on different
// platforms with different sizes. If it is greater than zero, it has been
// initialized to some meaningful value at least.
assert(
view.display.size > Offset.zero,
'Expected ${view.display} to be initialized.',
);
final ByteData data = ByteData(1);
data.setUint8(0, 1);
PlatformDispatcher.instance.sendPlatformMessage('waiting_for_status', data, null);
}
/// The FlutterView into which the [Scenario]s will be rendered.
FlutterView get _view => PlatformDispatcher.instance.implicitView!;
void _handleDriverMessage(ByteData? data, PlatformMessageResponseCallback? callback) {
final Map<String, dynamic> call = json.decode(utf8.decode(data!.buffer.asUint8List())) as Map<String, dynamic>;
final String? methodName = call['method'] as String?;
switch (methodName) {
case 'set_scenario':
assert(call['args'] != null);
loadScenario(call['args'] as Map<String, dynamic>, _view);
default:
throw 'Unimplemented method: $methodName.';
}
}
Future<void> _handleWriteTimelineMessage(ByteData? data, PlatformMessageResponseCallback? callback) async {
final String timelineData = await _getTimelineData();
callback!(ByteData.sublistView(utf8.encode(timelineData)));
}
Future<String> _getTimelineData() async {
final developer.ServiceProtocolInfo info = await developer.Service.getInfo();
final Uri vmServiceTimelineUri = info.serverUri!.resolve('getVMTimeline');
final Map<String, dynamic> vmServiceTimelineJson = await _getJson(vmServiceTimelineUri);
final Map<String, dynamic> vmServiceResult = vmServiceTimelineJson['result'] as Map<String, dynamic>;
return json.encode(<String, dynamic>{
'traceEvents': <dynamic>[
...vmServiceResult['traceEvents'] as List<dynamic>,
],
});
}
Future<Map<String, dynamic>> _getJson(Uri uri) async {
final HttpClient client = HttpClient();
final HttpClientRequest request = await client.getUrl(uri);
final HttpClientResponse response = await request.close();
if (response.statusCode > 299) {
return <String, dynamic>{};
}
final String data = await utf8.decodeStream(response);
return json.decode(data) as Map<String, dynamic>;
}
void _onBeginFrame(Duration duration) {
// Render an empty frame to signal first frame in the platform side.
if (currentScenario == null) {
final SceneBuilder builder = SceneBuilder();
final Scene scene = builder.build();
_view.render(scene);
scene.dispose();
return;
}
currentScenario!.onBeginFrame(duration);
}
void _onDrawFrame() {
currentScenario?.onDrawFrame();
}
void _onMetricsChanged() {
currentScenario?.onMetricsChanged();
}
void _onPointerDataPacket(PointerDataPacket packet) {
currentScenario?.onPointerDataPacket(packet);
}
| engine/testing/scenario_app/lib/main.dart/0 | {
"file_path": "engine/testing/scenario_app/lib/main.dart",
"repo_id": "engine",
"token_count": 1227
} | 441 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/testing/test_metal_context.h"
#include <Metal/Metal.h>
#include <iostream>
#include "flutter/fml/logging.h"
#include "flutter/fml/platform/darwin/scoped_nsobject.h"
#include "third_party/skia/include/core/SkSurface.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlBackendContext.h"
#include "third_party/skia/include/gpu/ganesh/mtl/GrMtlDirectContext.h"
namespace flutter {
TestMetalContext::TestMetalContext() {
auto device = fml::scoped_nsprotocol{MTLCreateSystemDefaultDevice()};
if (!device) {
FML_LOG(ERROR) << "Could not acquire Metal device.";
return;
}
auto command_queue = fml::scoped_nsobject{[device.get() newCommandQueue]};
if (!command_queue) {
FML_LOG(ERROR) << "Could not create the default command queue.";
return;
}
[command_queue.get() setLabel:@"Flutter Test Queue"];
GrMtlBackendContext backendContext = {};
// Skia expect arguments to `MakeMetal` transfer ownership of the reference in for release later
// when the GrDirectContext is collected.
backendContext.fDevice.reset([device.get() retain]);
backendContext.fQueue.reset([command_queue.get() retain]);
skia_context_ = GrDirectContexts::MakeMetal(backendContext);
if (!skia_context_) {
FML_LOG(ERROR) << "Could not create the GrDirectContext from the Metal Device "
"and command queue.";
}
device_ = [device.get() retain];
command_queue_ = [command_queue.get() retain];
}
TestMetalContext::~TestMetalContext() {
std::scoped_lock lock(textures_mutex_);
textures_.clear();
if (device_) {
[(__bridge id)device_ release];
}
if (command_queue_) {
[(__bridge id)command_queue_ release];
}
}
void* TestMetalContext::GetMetalDevice() const {
return device_;
}
void* TestMetalContext::GetMetalCommandQueue() const {
return command_queue_;
}
sk_sp<GrDirectContext> TestMetalContext::GetSkiaContext() const {
return skia_context_;
}
TestMetalContext::TextureInfo TestMetalContext::CreateMetalTexture(const SkISize& size) {
std::scoped_lock lock(textures_mutex_);
auto texture_descriptor = fml::scoped_nsobject{
[[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:size.width()
height:size.height()
mipmapped:NO] retain]};
// The most pessimistic option and disables all optimizations but allows tests
// the most flexible access to the surface. They may read and write to the
// surface from shaders or use as a pixel view.
texture_descriptor.get().usage = MTLTextureUsageUnknown;
if (!texture_descriptor) {
FML_CHECK(false) << "Invalid texture descriptor.";
return {.texture_id = -1, .texture = nullptr};
}
id<MTLDevice> device = (__bridge id<MTLDevice>)GetMetalDevice();
sk_cfp<void*> texture = sk_cfp<void*>{[device newTextureWithDescriptor:texture_descriptor.get()]};
if (!texture) {
FML_CHECK(false) << "Could not create texture from texture descriptor.";
return {.texture_id = -1, .texture = nullptr};
}
const int64_t texture_id = texture_id_ctr_++;
textures_[texture_id] = texture;
return {
.texture_id = texture_id,
.texture = texture.get(),
};
}
// Don't remove the texture from the map here.
bool TestMetalContext::Present(int64_t texture_id) {
std::scoped_lock lock(textures_mutex_);
if (textures_.find(texture_id) == textures_.end()) {
return false;
} else {
return true;
}
}
TestMetalContext::TextureInfo TestMetalContext::GetTextureInfo(int64_t texture_id) {
std::scoped_lock lock(textures_mutex_);
if (textures_.find(texture_id) == textures_.end()) {
FML_CHECK(false) << "Invalid texture id: " << texture_id;
return {.texture_id = -1, .texture = nullptr};
} else {
return {
.texture_id = texture_id,
.texture = textures_[texture_id].get(),
};
}
}
} // namespace flutter
| engine/testing/test_metal_context.mm/0 | {
"file_path": "engine/testing/test_metal_context.mm",
"repo_id": "engine",
"token_count": 1588
} | 442 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FLUTTER_TESTING_TESTING_H_
#define FLUTTER_TESTING_TESTING_H_
#include <string>
#include <vector>
#include "flutter/fml/file.h"
#include "flutter/fml/mapping.h"
#include "flutter/testing/assertions.h"
#include "gtest/gtest.h"
#include "third_party/skia/include/core/SkData.h"
namespace flutter {
namespace testing {
const char* GetSourcePath();
//------------------------------------------------------------------------------
/// @brief Returns the directory containing the test fixture for the target
/// if this target has fixtures configured. If there are no
/// fixtures, this is a link error. If you see a linker error on
/// this symbol, the unit-test target needs to depend on a
/// `test_fixtures` target.
///
/// @return The fixtures path.
///
const char* GetFixturesPath();
//------------------------------------------------------------------------------
/// @brief Returns the directory containing assets shared across all tests.
///
/// @return The testing assets path.
///
const char* GetTestingAssetsPath();
//------------------------------------------------------------------------------
/// @brief Returns the default path to kernel_blob.bin. This file is within
/// the directory returned by `GetFixturesPath()`.
///
/// @return The kernel file path.
///
std::string GetDefaultKernelFilePath();
//------------------------------------------------------------------------------
/// @brief Opens the fixtures directory for the unit-test harness.
///
/// @return The file descriptor of the fixtures directory.
///
fml::UniqueFD OpenFixturesDirectory();
//------------------------------------------------------------------------------
/// @brief Opens a fixture of the given file name.
///
/// @param[in] fixture_name The fixture name
///
/// @return The file descriptor of the given fixture. An invalid file
/// descriptor is returned in case the fixture is not found.
///
fml::UniqueFD OpenFixture(const std::string& fixture_name);
//------------------------------------------------------------------------------
/// @brief Opens a fixture of the given file name and returns a mapping to
/// its contents.
///
/// @param[in] fixture_name The fixture name
///
/// @return A mapping to the contents of fixture or null if the fixture does
/// not exist or its contents cannot be mapped in.
///
std::unique_ptr<fml::Mapping> OpenFixtureAsMapping(
const std::string& fixture_name);
//------------------------------------------------------------------------------
/// @brief Opens a fixture of the given file name and returns a Skia SkData
/// holding its contents.
///
/// @param[in] fixture_name The fixture name
///
/// @return An SkData, or null if the fixture does not exist or its contents
/// cannot be mapped in.
///
sk_sp<SkData> OpenFixtureAsSkData(const std::string& fixture_name);
//------------------------------------------------------------------------------
/// @brief Gets the name of the currently running test. This is useful in
/// generating logs or assets based on test name.
///
/// @return The current test name.
///
std::string GetCurrentTestName();
enum class MemsetPatternOp {
kMemsetPatternOpSetBuffer,
kMemsetPatternOpCheckBuffer,
};
//------------------------------------------------------------------------------
/// @brief Depending on the operation, either scribbles a known pattern
/// into the buffer or checks if that pattern is present in an
/// existing buffer. This is a portable variant of the
/// memset_pattern class of methods that also happen to do assert
/// that the same pattern exists.
///
/// @param buffer The buffer
/// @param[in] size The size
/// @param[in] op The operation
///
/// @return If the result of the operation was a success.
///
bool MemsetPatternSetOrCheck(uint8_t* buffer, size_t size, MemsetPatternOp op);
bool MemsetPatternSetOrCheck(std::vector<uint8_t>& buffer, MemsetPatternOp op);
} // namespace testing
} // namespace flutter
#endif // FLUTTER_TESTING_TESTING_H_
| engine/testing/testing.h/0 | {
"file_path": "engine/testing/testing.h",
"repo_id": "engine",
"token_count": 1308
} | 443 |
// Copyright 2017 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.
#ifndef UI_ACCESSIBILITY_AX_ACTION_HANDLER_H_
#define UI_ACCESSIBILITY_AX_ACTION_HANDLER_H_
#include "ax_action_handler_base.h"
#include "ax_export.h"
namespace ui {
// The class you normally want to inherit from other classes when you want to
// make them visible to accessibility clients, since it automatically registers
// a valid AXTreeID with the AXTreeIDRegistry when constructing the instance.
//
// If you need more control over how the AXTreeID associated to this class is
// set, please inherit directly from AXActionHandlerBase instead.
class AX_EXPORT AXActionHandler : public AXActionHandlerBase {
protected:
AXActionHandler();
};
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_ACTION_HANDLER_H_
| engine/third_party/accessibility/ax/ax_action_handler.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_action_handler.h",
"repo_id": "engine",
"token_count": 260
} | 444 |
// Copyright 2020 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.
#include "ax_event_intent.h"
#include "ax_enum_util.h"
namespace ui {
AXEventIntent::AXEventIntent() = default;
AXEventIntent::AXEventIntent(ax::mojom::Command command,
ax::mojom::TextBoundary text_boundary,
ax::mojom::MoveDirection move_direction)
: command(command),
text_boundary(text_boundary),
move_direction(move_direction) {}
AXEventIntent::~AXEventIntent() = default;
AXEventIntent::AXEventIntent(const AXEventIntent& intent) = default;
AXEventIntent& AXEventIntent::operator=(const AXEventIntent& intent) = default;
bool operator==(const AXEventIntent& a, const AXEventIntent& b) {
return a.command == b.command && a.text_boundary == b.text_boundary &&
a.move_direction == b.move_direction;
}
bool operator!=(const AXEventIntent& a, const AXEventIntent& b) {
return !(a == b);
}
std::string AXEventIntent::ToString() const {
return std::string("AXEventIntent(") + ui::ToString(command) + ',' +
ui::ToString(text_boundary) + ',' + ui::ToString(move_direction) + ')';
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_event_intent.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_event_intent.cc",
"repo_id": "engine",
"token_count": 493
} | 445 |
// Copyright 2019 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.
#ifndef UI_ACCESSIBILITY_AX_OFFSCREEN_RESULT_H_
#define UI_ACCESSIBILITY_AX_OFFSCREEN_RESULT_H_
namespace ui {
// The onscreen state of result bounds or points. Any object is offscreen if
// it is fully clipped or scrolled out of view by any of its ancestors so that
// it is not rendered on the screen. For a longer discussion on what offscreen
// means in the context of Chromium see the link below.
// https://chromium.googlesource.com/chromium/src/+/lkgr/docs/accessibility/offscreen.md
// kOnscreen: The resulting bound or point is onscreen
// kOffscreen: The resulting bound or point is offscreen
enum class AXOffscreenResult { kOnscreen, kOffscreen };
} // namespace ui
#endif // UI_ACCESSIBILITY_AX_OFFSCREEN_RESULT_H_
| engine/third_party/accessibility/ax/ax_offscreen_result.h/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_offscreen_result.h",
"repo_id": "engine",
"token_count": 279
} | 446 |
// Copyright 2018 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.
#include "ax_tree_id.h"
#include <algorithm>
#include <iostream>
#include "ax_enums.h"
#include "base/logging.h"
#include "base/no_destructor.h"
namespace ui {
AXTreeID::AXTreeID() : AXTreeID(ax::mojom::AXTreeIDType::kUnknown) {}
AXTreeID::AXTreeID(const AXTreeID& other) = default;
AXTreeID::AXTreeID(ax::mojom::AXTreeIDType type) : type_(type) {
if (type_ == ax::mojom::AXTreeIDType::kToken)
token_ = base::SimpleToken::Create();
}
AXTreeID::AXTreeID(const std::string& string) {
if (string.empty()) {
type_ = ax::mojom::AXTreeIDType::kUnknown;
} else {
type_ = ax::mojom::AXTreeIDType::kToken;
std::optional<base::SimpleToken> token = base::ValueToSimpleToken(string);
BASE_DCHECK(token);
token_ = *token;
}
}
// static
AXTreeID AXTreeID::FromString(const std::string& string) {
return AXTreeID(string);
}
// static
AXTreeID AXTreeID::FromToken(const base::SimpleToken& token) {
return AXTreeID(token.ToString());
}
// static
AXTreeID AXTreeID::CreateNewAXTreeID() {
return AXTreeID(ax::mojom::AXTreeIDType::kToken);
}
AXTreeID& AXTreeID::operator=(const AXTreeID& other) = default;
std::string AXTreeID::ToString() const {
switch (type_) {
case ax::mojom::AXTreeIDType::kUnknown:
return "";
case ax::mojom::AXTreeIDType::kToken:
return base::SimpleTokenToValue(*token_);
}
BASE_UNREACHABLE();
return std::string();
}
void swap(AXTreeID& first, AXTreeID& second) {
std::swap(first.type_, second.type_);
std::swap(first.token_, second.token_);
}
bool AXTreeID::operator==(const AXTreeID& rhs) const {
return type_ == rhs.type_ && token_ == rhs.token_;
}
bool AXTreeID::operator!=(const AXTreeID& rhs) const {
return !(*this == rhs);
}
bool AXTreeID::operator<(const AXTreeID& rhs) const {
return std::tie(type_, token_) < std::tie(rhs.type_, rhs.token_);
}
bool AXTreeID::operator<=(const AXTreeID& rhs) const {
return std::tie(type_, token_) <= std::tie(rhs.type_, rhs.token_);
}
bool AXTreeID::operator>(const AXTreeID& rhs) const {
return !(*this <= rhs);
}
bool AXTreeID::operator>=(const AXTreeID& rhs) const {
return !(*this < rhs);
}
size_t AXTreeIDHash::operator()(const ui::AXTreeID& tree_id) const {
BASE_DCHECK(tree_id.type() == ax::mojom::AXTreeIDType::kToken);
return base::SimpleTokenHash(tree_id.token().value());
}
std::ostream& operator<<(std::ostream& stream, const AXTreeID& value) {
return stream << value.ToString();
}
const AXTreeID& AXTreeIDUnknown() {
static const base::NoDestructor<AXTreeID> ax_tree_id_unknown(
ax::mojom::AXTreeIDType::kUnknown);
return *ax_tree_id_unknown;
}
} // namespace ui
| engine/third_party/accessibility/ax/ax_tree_id.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/ax_tree_id.cc",
"repo_id": "engine",
"token_count": 1134
} | 447 |
// Copyright 2014 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.
#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_
#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_
#include <functional>
#include <ostream>
#include <string>
#include "ax/ax_enums.h"
#include "ax/ax_export.h"
#include "ax/ax_mode.h"
#include "ax/ax_mode_observer.h"
#include "ax_build/build_config.h"
#include "base/macros.h"
#include "gfx/native_widget_types.h"
namespace ui {
class AXPlatformNodeDelegate;
// AXPlatformNode is the abstract base class for an implementation of
// native accessibility APIs on supported platforms (e.g. Windows, Mac OS X).
// An object that wants to be accessible can derive from AXPlatformNodeDelegate
// and then call AXPlatformNode::Create. The delegate implementation should
// own the AXPlatformNode instance (or otherwise manage its lifecycle).
class AX_EXPORT AXPlatformNode {
public:
typedef AXPlatformNode* NativeWindowHandlerCallback(gfx::NativeWindow);
// Create an appropriate platform-specific instance. The delegate owns the
// AXPlatformNode instance (or manages its lifecycle in some other way).
static AXPlatformNode* Create(AXPlatformNodeDelegate* delegate);
// Cast a gfx::NativeViewAccessible to an AXPlatformNode if it is one,
// or return nullptr if it's not an instance of this class.
static AXPlatformNode* FromNativeViewAccessible(
gfx::NativeViewAccessible accessible);
// Return the AXPlatformNode at the root of the tree for a native window.
static AXPlatformNode* FromNativeWindow(gfx::NativeWindow native_window);
// Provide a function that returns the AXPlatformNode at the root of the
// tree for a native window.
static void RegisterNativeWindowHandler(
std::function<NativeWindowHandlerCallback> handler);
// Register and unregister to receive notifications about AXMode changes
// for this node.
static void AddAXModeObserver(AXModeObserver* observer);
static void RemoveAXModeObserver(AXModeObserver* observer);
// Convenience method to get the current accessibility mode.
static AXMode GetAccessibilityMode() { return ax_mode_; }
// Helper static function to notify all global observers about
// the addition of an AXMode flag.
static void NotifyAddAXModeFlags(AXMode mode_flags);
// Return the focused object in any UI popup overlaying content, or null.
static gfx::NativeViewAccessible GetPopupFocusOverride();
// Set the focused object withn any UI popup overlaying content, or null.
// The focus override is the perceived focus within the popup, and it changes
// each time a user navigates to a new item within the popup.
static void SetPopupFocusOverride(gfx::NativeViewAccessible focus_override);
// Call Destroy rather than deleting this, because the subclass may
// use reference counting.
virtual void Destroy();
// Get the platform-specific accessible object type for this instance.
// On some platforms this is just a type cast, on others it may be a
// wrapper object or handle.
virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0;
// Fire a platform-specific notification that an event has occurred on
// this object.
virtual void NotifyAccessibilityEvent(ax::mojom::Event event_type) = 0;
#if defined(OS_APPLE)
// Fire a platform-specific notification to announce |text|.
virtual void AnnounceText(const std::u16string& text) = 0;
#endif
// Return this object's delegate.
virtual AXPlatformNodeDelegate* GetDelegate() const = 0;
// Return true if this object is equal to or a descendant of |ancestor|.
virtual bool IsDescendantOf(AXPlatformNode* ancestor) const = 0;
// Set |this| as the primary web contents for the window.
void SetIsPrimaryWebContentsForWindow(bool is_primary);
bool IsPrimaryWebContentsForWindow() const;
// Return the unique ID.
int32_t GetUniqueId() const;
// Creates a string representation of this node's data.
std::string ToString();
// Returns a string representation of the subtree of nodes rooted at this
// node.
std::string SubtreeToString();
friend std::ostream& operator<<(std::ostream& stream, AXPlatformNode& node);
virtual ~AXPlatformNode();
protected:
AXPlatformNode();
private:
static std::vector<AXModeObserver*> ax_mode_observers_;
static std::function<NativeWindowHandlerCallback> native_window_handler_;
static AXMode ax_mode_;
// This allows UI menu popups like to act as if they are focused in the
// exposed platform accessibility API, even though actual focus remains in
// underlying content.
static gfx::NativeViewAccessible popup_focus_override_;
bool is_primary_web_contents_for_window_ = false;
BASE_DISALLOW_COPY_AND_ASSIGN(AXPlatformNode);
};
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_
| engine/third_party/accessibility/ax/platform/ax_platform_node.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node.h",
"repo_id": "engine",
"token_count": 1376
} | 448 |
// Copyright 2019 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.
#include "ax/platform/ax_platform_node_textrangeprovider_win.h"
#include <UIAutomation.h>
#include <wrl/client.h>
#include <string_view>
#include "ax/ax_action_data.h"
#include "ax/ax_range.h"
#include "ax/platform/ax_platform_node_delegate.h"
#include "ax/platform/ax_platform_node_win.h"
#include "ax/platform/ax_platform_tree_manager.h"
#include "base/win/variant_vector.h"
#include "flutter/fml/platform/win/wstring_conversion.h"
#include "third_party/icu/source/i18n/unicode/usearch.h"
#define UIA_VALIDATE_TEXTRANGEPROVIDER_CALL() \
if (!GetOwner() || !GetOwner()->GetDelegate() || !start() || \
!start()->GetAnchor() || !end() || !end()->GetAnchor()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
SetStart(start()->AsValidPosition()); \
SetEnd(end()->AsValidPosition());
#define UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN(in) \
if (!GetOwner() || !GetOwner()->GetDelegate() || !start() || \
!start()->GetAnchor() || !end() || !end()->GetAnchor()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!in) \
return E_POINTER; \
SetStart(start()->AsValidPosition()); \
SetEnd(end()->AsValidPosition());
#define UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(out) \
if (!GetOwner() || !GetOwner()->GetDelegate() || !start() || \
!start()->GetAnchor() || !end() || !end()->GetAnchor()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!out) \
return E_POINTER; \
*out = {}; \
SetStart(start()->AsValidPosition()); \
SetEnd(end()->AsValidPosition());
#define UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN_1_OUT(in, out) \
if (!GetOwner() || !GetOwner()->GetDelegate() || !start() || \
!start()->GetAnchor() || !end() || !end()->GetAnchor()) \
return UIA_E_ELEMENTNOTAVAILABLE; \
if (!in || !out) \
return E_POINTER; \
*out = {}; \
SetStart(start()->AsValidPosition()); \
SetEnd(end()->AsValidPosition());
// Validate bounds calculated by AXPlatformNodeDelegate. Degenerate bounds
// indicate the interface is not yet supported on the platform.
#define UIA_VALIDATE_BOUNDS(bounds) \
if (bounds.OffsetFromOrigin().IsZero() && bounds.IsEmpty()) \
return UIA_E_NOTSUPPORTED;
namespace ui {
class AXRangePhysicalPixelRectDelegate : public AXRangeRectDelegate {
public:
explicit AXRangePhysicalPixelRectDelegate(
AXPlatformNodeTextRangeProviderWin* host)
: host_(host) {}
gfx::Rect GetInnerTextRangeBoundsRect(
AXTreeID tree_id,
AXNode::AXID node_id,
int start_offset,
int end_offset,
ui::AXClippingBehavior clipping_behavior,
AXOffscreenResult* offscreen_result) override {
AXPlatformNodeDelegate* delegate = host_->GetDelegate(tree_id, node_id);
BASE_DCHECK(delegate);
return delegate->GetInnerTextRangeBoundsRect(
start_offset, end_offset, ui::AXCoordinateSystem::kScreenPhysicalPixels,
clipping_behavior, offscreen_result);
}
gfx::Rect GetBoundsRect(AXTreeID tree_id,
AXNode::AXID node_id,
AXOffscreenResult* offscreen_result) override {
AXPlatformNodeDelegate* delegate = host_->GetDelegate(tree_id, node_id);
BASE_DCHECK(delegate);
return delegate->GetBoundsRect(
ui::AXCoordinateSystem::kScreenPhysicalPixels,
ui::AXClippingBehavior::kClipped, offscreen_result);
}
private:
AXPlatformNodeTextRangeProviderWin* host_;
};
AXPlatformNodeTextRangeProviderWin::AXPlatformNodeTextRangeProviderWin() {}
AXPlatformNodeTextRangeProviderWin::~AXPlatformNodeTextRangeProviderWin() {}
ITextRangeProvider* AXPlatformNodeTextRangeProviderWin::CreateTextRangeProvider(
AXPositionInstance start,
AXPositionInstance end) {
CComObject<AXPlatformNodeTextRangeProviderWin>* text_range_provider = nullptr;
if (SUCCEEDED(CComObject<AXPlatformNodeTextRangeProviderWin>::CreateInstance(
&text_range_provider))) {
BASE_DCHECK(text_range_provider);
text_range_provider->SetStart(std::move(start));
text_range_provider->SetEnd(std::move(end));
text_range_provider->AddRef();
return text_range_provider;
}
return nullptr;
}
ITextRangeProvider*
AXPlatformNodeTextRangeProviderWin::CreateTextRangeProviderForTesting(
AXPlatformNodeWin* owner,
AXPositionInstance start,
AXPositionInstance end) {
Microsoft::WRL::ComPtr<ITextRangeProvider> text_range_provider =
CreateTextRangeProvider(start->Clone(), end->Clone());
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin>
text_range_provider_win;
if (SUCCEEDED(text_range_provider->QueryInterface(
IID_PPV_ARGS(&text_range_provider_win)))) {
text_range_provider_win->SetOwnerForTesting(owner); // IN-TEST
return text_range_provider_win.Get();
}
return nullptr;
}
//
// ITextRangeProvider methods.
//
HRESULT AXPlatformNodeTextRangeProviderWin::Clone(ITextRangeProvider** clone) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(clone);
*clone = CreateTextRangeProvider(start()->Clone(), end()->Clone());
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::Compare(ITextRangeProvider* other,
BOOL* result) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN_1_OUT(other, result);
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin> other_provider;
if (other->QueryInterface(IID_PPV_ARGS(&other_provider)) != S_OK)
return UIA_E_INVALIDOPERATION;
if (*start() == *(other_provider->start()) &&
*end() == *(other_provider->end())) {
*result = TRUE;
}
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::CompareEndpoints(
TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint,
int* result) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN_1_OUT(other, result);
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin> other_provider;
if (other->QueryInterface(IID_PPV_ARGS(&other_provider)) != S_OK)
return UIA_E_INVALIDOPERATION;
const AXPositionInstance& this_provider_endpoint =
(this_endpoint == TextPatternRangeEndpoint_Start) ? start() : end();
const AXPositionInstance& other_provider_endpoint =
(other_endpoint == TextPatternRangeEndpoint_Start)
? other_provider->start()
: other_provider->end();
std::optional<int> comparison =
this_provider_endpoint->CompareTo(*other_provider_endpoint);
if (!comparison)
return UIA_E_INVALIDOPERATION;
if (comparison.value() < 0)
*result = -1;
else if (comparison.value() > 0)
*result = 1;
else
*result = 0;
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::ExpandToEnclosingUnit(
TextUnit unit) {
return ExpandToEnclosingUnitImpl(unit);
}
HRESULT AXPlatformNodeTextRangeProviderWin::ExpandToEnclosingUnitImpl(
TextUnit unit) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL();
{
AXPositionInstance normalized_start = start()->Clone();
AXPositionInstance normalized_end = end()->Clone();
NormalizeTextRange(normalized_start, normalized_end);
SetStart(std::move(normalized_start));
SetEnd(std::move(normalized_end));
}
// Determine if start is on a boundary of the specified TextUnit, if it is
// not, move backwards until it is. Move the end forwards from start until it
// is on the next TextUnit boundary, if one exists.
switch (unit) {
case TextUnit_Character: {
// For characters, the start endpoint will always be on a TextUnit
// boundary, thus we only need to move the end position.
AXPositionInstance end_backup = end()->Clone();
SetEnd(start()->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary));
if (end()->IsNullPosition()) {
// The previous could fail if the start is at the end of the last anchor
// of the tree, try expanding to the previous character instead.
AXPositionInstance start_backup = start()->Clone();
SetStart(start()->CreatePreviousCharacterPosition(
AXBoundaryBehavior::CrossBoundary));
if (start()->IsNullPosition()) {
// Text representation is empty, undo everything and exit.
SetStart(std::move(start_backup));
SetEnd(std::move(end_backup));
return S_OK;
}
SetEnd(start()->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary));
BASE_DCHECK(!end()->IsNullPosition());
}
AXPositionInstance normalized_start = start()->Clone();
AXPositionInstance normalized_end = end()->Clone();
NormalizeTextRange(normalized_start, normalized_end);
SetStart(std::move(normalized_start));
SetEnd(std::move(normalized_end));
break;
}
case TextUnit_Format:
SetStart(start()->CreatePreviousFormatStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
SetEnd(start()->CreateNextFormatEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
break;
case TextUnit_Word: {
AXPositionInstance start_backup = start()->Clone();
SetStart(start()->CreatePreviousWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
// Since start_ is already located at a word boundary, we need to cross it
// in order to move to the next one. Because Windows ATs behave
// undesirably when the start and end endpoints are not in the same anchor
// (for character and word navigation), stop at anchor boundary.
SetEnd(start()->CreateNextWordStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
break;
}
case TextUnit_Line:
// Walk backwards to the previous line start (but don't walk backwards
// if we're already at the start of a line). The previous line start can
// occur in a different node than where `start` is currently pointing, so
// use kStopAtLastAnchorBoundary, which will stop at the tree boundary if
// no previous line start is found.
SetStart(start()->CreateBoundaryStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary,
ax::mojom::MoveDirection::kBackward, &AtStartOfLinePredicate,
&AtEndOfLinePredicate));
// From the start we just walked backwards to, walk forwards to the line
// end position.
SetEnd(start()->CreateBoundaryEndPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary,
ax::mojom::MoveDirection::kForward, &AtStartOfLinePredicate,
&AtEndOfLinePredicate));
break;
case TextUnit_Paragraph:
SetStart(start()->CreatePreviousParagraphStartPosition(
AXBoundaryBehavior::StopIfAlreadyAtBoundary));
SetEnd(start()->CreateNextParagraphStartPosition(
AXBoundaryBehavior::StopAtLastAnchorBoundary));
break;
case TextUnit_Page: {
// Per UIA spec, if the document containing the current range doesn't
// support pagination, default to document navigation.
const AXNode* common_anchor = start()->LowestCommonAnchor(*end());
if (common_anchor->tree()->HasPaginationSupport()) {
SetStart(start()->CreatePreviousPageStartPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
SetEnd(start()->CreateNextPageEndPosition(
AXBoundaryBehavior::StopAtAnchorBoundary));
break;
}
}
[[fallthrough]];
case TextUnit_Document:
SetStart(
start()->CreatePositionAtStartOfDocument()->AsLeafTextPosition());
SetEnd(start()->CreatePositionAtEndOfDocument());
break;
default:
return UIA_E_NOTSUPPORTED;
}
BASE_DCHECK(!start()->IsNullPosition());
BASE_DCHECK(!end()->IsNullPosition());
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::FindAttribute(
TEXTATTRIBUTEID text_attribute_id,
VARIANT attribute_val,
BOOL is_backward,
ITextRangeProvider** result) {
// Algorithm description:
// Performs linear search. Expand forward or backward to fetch the first
// instance of a sub text range that matches the attribute and its value.
// |is_backward| determines the direction of our search.
// |is_backward=true|, we search from the end of this text range to its
// beginning.
// |is_backward=false|, we search from the beginning of this text range to its
// end.
//
// 1. Iterate through the vector of AXRanges in this text range in the
// direction denoted by |is_backward|.
// 2. The |matched_range| is initially denoted as null since no range
// currently matches. We initialize |matched_range| to non-null value when
// we encounter the first AXRange instance that matches in attribute and
// value. We then set the |matched_range_start| to be the start (anchor) of
// the current AXRange, and |matched_range_end| to be the end (focus) of
// the current AXRange.
// 3. If the current AXRange we are iterating on continues to match attribute
// and value, we extend |matched_range| in one of the two following ways:
// - If |is_backward=true|, we extend the |matched_range| by moving
// |matched_range_start| backward. We do so by setting
// |matched_range_start| to the start (anchor) of the current AXRange.
// - If |is_backward=false|, we extend the |matched_range| by moving
// |matched_range_end| forward. We do so by setting |matched_range_end|
// to the end (focus) of the current AXRange.
// 4. We found a match when the current AXRange we are iterating on does not
// match the attribute and value and there is a previously matched range.
// The previously matched range is the final match we found.
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(result);
// Use a cloned range so that FindAttribute does not introduce side-effects
// while normalizing the original range.
AXPositionInstance normalized_start = start()->Clone();
AXPositionInstance normalized_end = end()->Clone();
NormalizeTextRange(normalized_start, normalized_end);
*result = nullptr;
AXPositionInstance matched_range_start = nullptr;
AXPositionInstance matched_range_end = nullptr;
std::vector<AXNodeRange> anchors;
AXNodeRange range(normalized_start->Clone(), normalized_end->Clone());
for (AXNodeRange leaf_text_range : range)
anchors.emplace_back(std::move(leaf_text_range));
auto expand_match = [&matched_range_start, &matched_range_end, is_backward](
auto& current_start, auto& current_end) {
// The current AXRange has the attribute and its value that we are looking
// for, we expand the matched text range if a previously matched exists,
// otherwise initialize a newly matched text range.
if (matched_range_start != nullptr && matched_range_end != nullptr) {
// Continue expanding the matched text range forward/backward based on
// the search direction.
if (is_backward)
matched_range_start = current_start->Clone();
else
matched_range_end = current_end->Clone();
} else {
// Initialize the matched text range. The first AXRange instance that
// matches the attribute and its value encountered.
matched_range_start = current_start->Clone();
matched_range_end = current_end->Clone();
}
};
HRESULT hr_result =
is_backward
? FindAttributeRange(text_attribute_id, attribute_val,
anchors.crbegin(), anchors.crend(), expand_match)
: FindAttributeRange(text_attribute_id, attribute_val,
anchors.cbegin(), anchors.cend(), expand_match);
if (FAILED(hr_result))
return E_FAIL;
if (matched_range_start != nullptr && matched_range_end != nullptr)
*result = CreateTextRangeProvider(std::move(matched_range_start),
std::move(matched_range_end));
return S_OK;
}
template <typename AnchorIterator, typename ExpandMatchLambda>
HRESULT AXPlatformNodeTextRangeProviderWin::FindAttributeRange(
const TEXTATTRIBUTEID text_attribute_id,
VARIANT attribute_val,
const AnchorIterator first,
const AnchorIterator last,
ExpandMatchLambda expand_match) {
AXPlatformNodeWin* current_platform_node;
bool is_match_found = false;
for (auto it = first; it != last; ++it) {
const auto& current_start = it->anchor();
const auto& current_end = it->focus();
BASE_DCHECK(current_start->GetAnchor() == current_end->GetAnchor());
AXPlatformNodeDelegate* delegate = GetDelegate(current_start);
BASE_DCHECK(delegate);
current_platform_node = static_cast<AXPlatformNodeWin*>(
delegate->GetFromNodeID(current_start->GetAnchor()->id()));
base::win::VariantVector current_attribute_value;
if (FAILED(current_platform_node->GetTextAttributeValue(
text_attribute_id, current_start->text_offset(),
current_end->text_offset(), ¤t_attribute_value))) {
return E_FAIL;
}
if (!current_attribute_value.Compare(attribute_val)) {
// When we encounter an AXRange instance that matches the attribute
// and its value which we are looking for and no previously matched text
// range exists, we expand or initialize the matched range.
is_match_found = true;
expand_match(current_start, current_end);
} else if (is_match_found) {
// When we encounter an AXRange instance that does not match the attribute
// and its value which we are looking for and a previously matched text
// range exists, the previously matched text range is the result we found.
break;
}
}
return S_OK;
}
static bool StringSearchBasic(const std::u16string_view search_string,
const std::u16string_view find_in,
size_t* find_start,
size_t* find_length,
bool backwards) {
size_t index =
backwards ? find_in.rfind(search_string) : find_in.find(search_string);
if (index == std::u16string::npos) {
return false;
}
*find_start = index;
*find_length = search_string.size();
return true;
}
bool StringSearch(std::u16string_view search_string,
std::u16string_view find_in,
size_t* find_start,
size_t* find_length,
bool ignore_case,
bool backwards) {
UErrorCode status = U_ZERO_ERROR;
UCollator* col = ucol_open(uloc_getDefault(), &status);
UStringSearch* search = usearch_openFromCollator(
search_string.data(), search_string.size(), find_in.data(),
find_in.size(), col, nullptr, &status);
if (!U_SUCCESS(status)) {
if (search) {
usearch_close(search);
}
return StringSearchBasic(search_string, find_in, find_start, find_length,
backwards);
}
UCollator* collator = usearch_getCollator(search);
ucol_setStrength(collator, ignore_case ? UCOL_PRIMARY : UCOL_TERTIARY);
usearch_reset(search);
status = U_ZERO_ERROR;
usearch_setText(search, find_in.data(), find_in.size(), &status);
if (!U_SUCCESS(status)) {
if (search) {
usearch_close(search);
}
return StringSearchBasic(search_string, find_in, find_start, find_length,
backwards);
}
int32_t index = backwards ? usearch_last(search, &status)
: usearch_first(search, &status);
bool match = false;
if (U_SUCCESS(status) && index != USEARCH_DONE) {
match = true;
*find_start = static_cast<size_t>(index);
*find_length = static_cast<size_t>(usearch_getMatchedLength(search));
}
usearch_close(search);
return match;
}
HRESULT AXPlatformNodeTextRangeProviderWin::FindText(
BSTR string,
BOOL backwards,
BOOL ignore_case,
ITextRangeProvider** result) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN_1_OUT(string, result);
// On Windows, there's a dichotomy in the definition of a text offset in a
// text position between different APIs:
// - on UIA, a text offset translates to the offset in the text itself
// - on IA2, it translates to the offset in the hypertext
//
// All unignored non-text nodes are represented with an "embedded object
// character" in their parent's text representation on IA2, but aren't on UIA.
// This leads to different expected MaxTextOffset values for a same text
// position. If `string` is found in the text represented by the start/end
// endpoints, we'll create text positions in the least common ancestor, use
// the flat text representation's offsets of found string, then convert the
// positions to leaf. If 'embedded object characters' are considered, instead
// of the flat text representation, this falls apart.
//
// Whether we expose embedded object characters for nodes is managed by the
// |g_ax_embedded_object_behavior| global variable set in ax_node_position.cc.
// When on Windows, this variable is always set to kExposeCharacter... which
// is incorrect if we run UIA-specific code. To avoid problems caused by that,
// we use the following ScopedAXEmbeddedObjectBehaviorSetter to modify the
// value of the global variable to what is really expected on UIA.
ScopedAXEmbeddedObjectBehaviorSetter ax_embedded_object_behavior(
AXEmbeddedObjectBehavior::kSuppressCharacter);
std::u16string search_string = fml::WideStringToUtf16(string);
if (search_string.length() <= 0)
return E_INVALIDARG;
size_t appended_newlines_count = 0;
std::u16string text_range = GetString(-1, &appended_newlines_count);
size_t find_start;
size_t find_length;
if (StringSearch(search_string, text_range, &find_start, &find_length,
ignore_case, backwards) &&
find_length > appended_newlines_count) {
// TODO(https://crbug.com/1023599): There is a known issue here related to
// text searches of a |string| starting and ending with a "\n", e.g.
// "\nsometext" or "sometext\n" if the newline is computed from a line
// breaking object. FindText() is rarely called, and when it is, it's not to
// look for a string starting or ending with a newline. This may change
// someday, and if so, we'll have to address this issue.
const AXNode* common_anchor = start()->LowestCommonAnchor(*end());
AXPositionInstance start_ancestor_position =
start()->CreateAncestorPosition(common_anchor,
ax::mojom::MoveDirection::kForward);
BASE_DCHECK(!start_ancestor_position->IsNullPosition());
AXPositionInstance end_ancestor_position = end()->CreateAncestorPosition(
common_anchor, ax::mojom::MoveDirection::kForward);
BASE_DCHECK(!end_ancestor_position->IsNullPosition());
const AXNode* anchor = start_ancestor_position->GetAnchor();
BASE_DCHECK(anchor);
const int start_offset =
start_ancestor_position->text_offset() + find_start;
const int end_offset = start_offset + find_length - appended_newlines_count;
const int max_end_offset = end_ancestor_position->text_offset();
BASE_DCHECK(start_offset <= end_offset && end_offset <= max_end_offset);
AXPositionInstance start =
ui::AXNodePosition::CreateTextPosition(
anchor->tree()->GetAXTreeID(), anchor->id(), start_offset,
ax::mojom::TextAffinity::kDownstream)
->AsLeafTextPosition();
AXPositionInstance end =
ui::AXNodePosition::CreateTextPosition(
anchor->tree()->GetAXTreeID(), anchor->id(), end_offset,
ax::mojom::TextAffinity::kDownstream)
->AsLeafTextPosition();
*result = CreateTextRangeProvider(start->Clone(), end->Clone());
}
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::GetAttributeValue(
TEXTATTRIBUTEID attribute_id,
VARIANT* value) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(value);
base::win::VariantVector attribute_value;
// When the range spans only a generated newline (a generated newline is not
// part of a node, but rather introduced by AXRange::GetText when at a
// paragraph boundary), it doesn't make sense to return the readonly value of
// the start or end anchor since the newline character is not part of any of
// those nodes. Thus, this attribute value is independent from these nodes.
//
// Instead, we should return the readonly attribute value of the common anchor
// for these two endpoints since the newline character has more in common with
// its ancestor than its siblings. Important: This might not be true for all
// attributes, but it appears to be reasonable enough for the readonly one.
//
// To determine if the range encompasses *only* a generated newline, we need
// to validate that both the start and end endpoints are around the same
// paragraph boundary.
if (attribute_id == UIA_IsReadOnlyAttributeId &&
start()->anchor_id() != end()->anchor_id() &&
start()->AtEndOfParagraph() && end()->AtStartOfParagraph() &&
*start()->CreateNextCharacterPosition(
AXBoundaryBehavior::CrossBoundary) == *end()) {
AXPlatformNodeWin* common_anchor = GetLowestAccessibleCommonPlatformNode();
BASE_DCHECK(common_anchor);
HRESULT hr = common_anchor->GetTextAttributeValue(
attribute_id, std::nullopt, std::nullopt, &attribute_value);
if (FAILED(hr))
return E_FAIL;
*value = attribute_value.ReleaseAsScalarVariant();
return S_OK;
}
// Use a cloned range so that GetAttributeValue does not introduce
// side-effects while normalizing the original range.
AXPositionInstance normalized_start = start()->Clone();
AXPositionInstance normalized_end = end()->Clone();
NormalizeTextRange(normalized_start, normalized_end);
// The range is inclusive, so advance our endpoint to the next position
const auto end_leaf_text_position = normalized_end->AsLeafTextPosition();
auto end = end_leaf_text_position->CreateNextAnchorPosition();
// Iterate over anchor positions
for (auto it = normalized_start->AsLeafTextPosition();
it->anchor_id() != end->anchor_id() || it->tree_id() != end->tree_id();
it = it->CreateNextAnchorPosition()) {
// If the iterator creates a null position, then it has likely overrun the
// range, return failure. This is unexpected but may happen if the range
// became inverted.
BASE_DCHECK(!it->IsNullPosition());
if (it->IsNullPosition())
return E_FAIL;
AXPlatformNodeDelegate* delegate = GetDelegate(it.get());
BASE_DCHECK(it && delegate);
AXPlatformNodeWin* platform_node = static_cast<AXPlatformNodeWin*>(
delegate->GetFromNodeID(it->anchor_id()));
BASE_DCHECK(platform_node);
// Only get attributes for nodes in the tree. Exclude descendants of leaves
// and ignored objects.
platform_node = static_cast<AXPlatformNodeWin*>(
AXPlatformNode::FromNativeViewAccessible(
platform_node->GetDelegate()->GetLowestPlatformAncestor()));
BASE_DCHECK(platform_node);
base::win::VariantVector current_value;
const bool at_end_leaf_text_anchor =
it->anchor_id() == end_leaf_text_position->anchor_id() &&
it->tree_id() == end_leaf_text_position->tree_id();
const std::optional<int> start_offset =
it->IsTextPosition() ? std::make_optional(it->text_offset())
: std::nullopt;
const std::optional<int> end_offset =
at_end_leaf_text_anchor
? std::make_optional(end_leaf_text_position->text_offset())
: std::nullopt;
HRESULT hr = platform_node->GetTextAttributeValue(
attribute_id, start_offset, end_offset, ¤t_value);
if (FAILED(hr))
return E_FAIL;
if (attribute_value.Type() == VT_EMPTY) {
attribute_value = std::move(current_value);
} else if (attribute_value != current_value) {
V_VT(value) = VT_UNKNOWN;
return ::UiaGetReservedMixedAttributeValue(&V_UNKNOWN(value));
}
}
if (ShouldReleaseTextAttributeAsSafearray(attribute_id, attribute_value))
*value = attribute_value.ReleaseAsSafearrayVariant();
else
*value = attribute_value.ReleaseAsScalarVariant();
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::GetBoundingRectangles(
SAFEARRAY** screen_physical_pixel_rectangles) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(screen_physical_pixel_rectangles);
*screen_physical_pixel_rectangles = nullptr;
AXNodeRange range(start()->Clone(), end()->Clone());
AXRangePhysicalPixelRectDelegate rect_delegate(this);
std::vector<gfx::Rect> rects = range.GetRects(&rect_delegate);
// 4 array items per rect: left, top, width, height
SAFEARRAY* safe_array = SafeArrayCreateVector(
VT_R8 /* element type */, 0 /* lower bound */, rects.size() * 4);
if (!safe_array)
return E_OUTOFMEMORY;
if (rects.size() > 0) {
double* double_array = nullptr;
HRESULT hr = SafeArrayAccessData(safe_array,
reinterpret_cast<void**>(&double_array));
if (SUCCEEDED(hr)) {
for (size_t rect_index = 0; rect_index < rects.size(); rect_index++) {
const gfx::Rect& rect = rects[rect_index];
double_array[rect_index * 4] = rect.x();
double_array[rect_index * 4 + 1] = rect.y();
double_array[rect_index * 4 + 2] = rect.width();
double_array[rect_index * 4 + 3] = rect.height();
}
hr = SafeArrayUnaccessData(safe_array);
}
if (FAILED(hr)) {
BASE_DCHECK(safe_array);
SafeArrayDestroy(safe_array);
return E_FAIL;
}
}
*screen_physical_pixel_rectangles = safe_array;
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::GetEnclosingElement(
IRawElementProviderSimple** element) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(element);
AXPlatformNodeWin* enclosing_node = GetLowestAccessibleCommonPlatformNode();
if (!enclosing_node)
return UIA_E_ELEMENTNOTAVAILABLE;
enclosing_node->GetNativeViewAccessible()->QueryInterface(
IID_PPV_ARGS(element));
BASE_DCHECK(*element);
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::GetText(int max_count, BSTR* text) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(text);
// -1 is a valid value that signifies that the caller wants complete text.
// Any other negative value is an invalid argument.
if (max_count < -1)
return E_INVALIDARG;
std::wstring full_text = fml::Utf16ToWideString(GetString(max_count));
if (!full_text.empty()) {
size_t length = full_text.length();
if (max_count != -1 && max_count < static_cast<int>(length))
*text = SysAllocStringLen(full_text.c_str(), max_count);
else
*text = SysAllocStringLen(full_text.c_str(), length);
} else {
*text = SysAllocString(L"");
}
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::Move(TextUnit unit,
int count,
int* units_moved) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(units_moved);
// Per MSDN, move with zero count has no effect.
if (count == 0)
return S_OK;
// Save a clone of start and end, in case one of the moves fails.
auto start_backup = start()->Clone();
auto end_backup = end()->Clone();
bool is_degenerate_range = (*start() == *end());
// Move the start of the text range forward or backward in the document by the
// requested number of text unit boundaries.
int start_units_moved = 0;
HRESULT hr = MoveEndpointByUnitImpl(TextPatternRangeEndpoint_Start, unit,
count, &start_units_moved);
bool succeeded_move = SUCCEEDED(hr) && start_units_moved != 0;
if (succeeded_move) {
SetEnd(start()->Clone());
if (!is_degenerate_range) {
bool forwards = count > 0;
if (forwards && start()->AtEndOfDocument()) {
// The start is at the end of the document, so move the start backward
// by one text unit to expand the text range from the degenerate range
// state.
int current_start_units_moved = 0;
hr = MoveEndpointByUnitImpl(TextPatternRangeEndpoint_Start, unit, -1,
¤t_start_units_moved);
start_units_moved -= 1;
succeeded_move = SUCCEEDED(hr) && current_start_units_moved == -1 &&
start_units_moved > 0;
} else {
// The start is not at the end of the document, so move the endpoint
// forward by one text unit to expand the text range from the degenerate
// state.
int end_units_moved = 0;
hr = MoveEndpointByUnitImpl(TextPatternRangeEndpoint_End, unit, 1,
&end_units_moved);
succeeded_move = SUCCEEDED(hr) && end_units_moved == 1;
}
// Because Windows ATs behave undesirably when the start and end endpoints
// are not in the same anchor (for character and word navigation), make
// sure to bring back the end endpoint to the end of the start's anchor.
if (start()->anchor_id() != end()->anchor_id() &&
(unit == TextUnit_Character || unit == TextUnit_Word)) {
ExpandToEnclosingUnitImpl(unit);
}
}
}
if (!succeeded_move) {
SetStart(std::move(start_backup));
SetEnd(std::move(end_backup));
start_units_moved = 0;
if (!SUCCEEDED(hr))
return hr;
}
*units_moved = start_units_moved;
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::MoveEndpointByUnit(
TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved) {
return MoveEndpointByUnitImpl(endpoint, unit, count, units_moved);
}
HRESULT AXPlatformNodeTextRangeProviderWin::MoveEndpointByUnitImpl(
TextPatternRangeEndpoint endpoint,
TextUnit unit,
int count,
int* units_moved) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(units_moved);
// Per MSDN, MoveEndpointByUnit with zero count has no effect.
if (count == 0) {
*units_moved = 0;
return S_OK;
}
bool is_start_endpoint = endpoint == TextPatternRangeEndpoint_Start;
AXPositionInstance position_to_move =
is_start_endpoint ? start()->Clone() : end()->Clone();
AXPositionInstance new_position;
// TODO(schectman): TextUnit_Format implementation.
// https://github.com/flutter/flutter/issues/117792
switch (unit) {
case TextUnit_Character:
new_position =
MoveEndpointByCharacter(position_to_move, count, units_moved);
break;
case TextUnit_Word:
new_position = MoveEndpointByWord(position_to_move, count, units_moved);
break;
case TextUnit_Line:
new_position = MoveEndpointByLine(position_to_move, is_start_endpoint,
count, units_moved);
break;
case TextUnit_Paragraph:
new_position = MoveEndpointByParagraph(
position_to_move, is_start_endpoint, count, units_moved);
break;
case TextUnit_Page:
new_position = MoveEndpointByPage(position_to_move, is_start_endpoint,
count, units_moved);
break;
case TextUnit_Document:
new_position =
MoveEndpointByDocument(position_to_move, count, units_moved);
break;
default:
return UIA_E_NOTSUPPORTED;
}
if (is_start_endpoint)
SetStart(std::move(new_position));
else
SetEnd(std::move(new_position));
// If the start was moved past the end, create a degenerate range with the end
// equal to the start; do the equivalent if the end moved past the start.
std::optional<int> endpoint_comparison =
AXNodeRange::CompareEndpoints(start().get(), end().get());
BASE_DCHECK(endpoint_comparison.has_value());
if (endpoint_comparison.value_or(0) > 0) {
if (is_start_endpoint)
SetEnd(start()->Clone());
else
SetStart(end()->Clone());
}
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::MoveEndpointByRange(
TextPatternRangeEndpoint this_endpoint,
ITextRangeProvider* other,
TextPatternRangeEndpoint other_endpoint) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_IN(other);
Microsoft::WRL::ComPtr<AXPlatformNodeTextRangeProviderWin> other_provider;
if (other->QueryInterface(IID_PPV_ARGS(&other_provider)) != S_OK)
return UIA_E_INVALIDOPERATION;
const AXPositionInstance& other_provider_endpoint =
(other_endpoint == TextPatternRangeEndpoint_Start)
? other_provider->start()
: other_provider->end();
if (this_endpoint == TextPatternRangeEndpoint_Start) {
SetStart(other_provider_endpoint->Clone());
if (*start() > *end())
SetEnd(start()->Clone());
} else {
SetEnd(other_provider_endpoint->Clone());
if (*start() > *end())
SetStart(end()->Clone());
}
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::Select() {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL();
AXPositionInstance selection_start = start()->Clone();
AXPositionInstance selection_end = end()->Clone();
// Blink only supports selections within a single tree. So if start_ and end_
// are in different trees, we can't directly pass them to the render process
// for selection.
if (selection_start->tree_id() != selection_end->tree_id()) {
// Prioritize the end position's tree, as a selection's focus object is the
// end of a selection.
selection_start = selection_end->CreatePositionAtStartOfAXTree();
}
BASE_DCHECK(!selection_start->IsNullPosition());
BASE_DCHECK(!selection_end->IsNullPosition());
BASE_DCHECK(selection_start->tree_id() == selection_end->tree_id());
// TODO(crbug.com/1124051): Blink does not support selection on the list
// markers. So if |selection_start| or |selection_end| are in list markers, we
// don't perform selection and return success. Remove this check once this bug
// is fixed.
if (selection_start->GetAnchor()->IsInListMarker() ||
selection_end->GetAnchor()->IsInListMarker()) {
return S_OK;
}
AXPlatformNodeDelegate* delegate =
GetDelegate(selection_start->tree_id(), selection_start->anchor_id());
BASE_DCHECK(delegate);
AXNodeRange new_selection_range(std::move(selection_start),
std::move(selection_end));
RemoveFocusFromPreviousSelectionIfNeeded(new_selection_range);
AXActionData action_data;
action_data.anchor_node_id = new_selection_range.anchor()->anchor_id();
action_data.anchor_offset = new_selection_range.anchor()->text_offset();
action_data.focus_node_id = new_selection_range.focus()->anchor_id();
action_data.focus_offset = new_selection_range.focus()->text_offset();
action_data.action = ax::mojom::Action::kSetSelection;
delegate->AccessibilityPerformAction(action_data);
return S_OK;
}
HRESULT AXPlatformNodeTextRangeProviderWin::AddToSelection() {
// Blink does not support disjoint text selections.
return UIA_E_INVALIDOPERATION;
}
HRESULT
AXPlatformNodeTextRangeProviderWin::RemoveFromSelection() {
// Blink does not support disjoint text selections.
return UIA_E_INVALIDOPERATION;
}
HRESULT AXPlatformNodeTextRangeProviderWin::ScrollIntoView(BOOL align_to_top) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL();
const AXPositionInstance start_common_ancestor =
start()->LowestCommonAncestor(*end());
const AXPositionInstance end_common_ancestor =
end()->LowestCommonAncestor(*start());
if (start_common_ancestor->IsNullPosition() ||
end_common_ancestor->IsNullPosition()) {
return E_INVALIDARG;
}
const AXNode* common_ancestor_anchor = start_common_ancestor->GetAnchor();
BASE_DCHECK(common_ancestor_anchor == end_common_ancestor->GetAnchor());
const AXTreeID common_ancestor_tree_id = start_common_ancestor->tree_id();
const AXPlatformNodeDelegate* root_delegate =
GetRootDelegate(common_ancestor_tree_id);
BASE_DCHECK(root_delegate);
const gfx::Rect root_frame_bounds = root_delegate->GetBoundsRect(
AXCoordinateSystem::kFrame, AXClippingBehavior::kUnclipped);
UIA_VALIDATE_BOUNDS(root_frame_bounds);
const AXPlatformNode* common_ancestor_platform_node =
GetOwner()->GetDelegate()->GetFromTreeIDAndNodeID(
common_ancestor_tree_id, common_ancestor_anchor->id());
BASE_DCHECK(common_ancestor_platform_node);
AXPlatformNodeDelegate* common_ancestor_delegate =
common_ancestor_platform_node->GetDelegate();
BASE_DCHECK(common_ancestor_delegate);
const gfx::Rect text_range_container_frame_bounds =
common_ancestor_delegate->GetBoundsRect(AXCoordinateSystem::kFrame,
AXClippingBehavior::kUnclipped);
UIA_VALIDATE_BOUNDS(text_range_container_frame_bounds);
gfx::Point target_point;
if (align_to_top) {
target_point = gfx::Point(root_frame_bounds.x(), root_frame_bounds.y());
} else {
target_point =
gfx::Point(root_frame_bounds.x(),
root_frame_bounds.y() + root_frame_bounds.height());
}
if ((align_to_top && start()->GetAnchor()->IsText()) ||
(!align_to_top && end()->GetAnchor()->IsText())) {
const gfx::Rect text_range_frame_bounds =
common_ancestor_delegate->GetInnerTextRangeBoundsRect(
start_common_ancestor->text_offset(),
end_common_ancestor->text_offset(), AXCoordinateSystem::kFrame,
AXClippingBehavior::kUnclipped);
UIA_VALIDATE_BOUNDS(text_range_frame_bounds);
if (align_to_top) {
target_point.Offset(0, -(text_range_container_frame_bounds.height() -
text_range_frame_bounds.height()));
} else {
target_point.Offset(0, -text_range_frame_bounds.height());
}
} else {
if (!align_to_top)
target_point.Offset(0, -text_range_container_frame_bounds.height());
}
const gfx::Rect root_screen_bounds = root_delegate->GetBoundsRect(
AXCoordinateSystem::kScreenDIPs, AXClippingBehavior::kUnclipped);
UIA_VALIDATE_BOUNDS(root_screen_bounds);
target_point += root_screen_bounds.OffsetFromOrigin();
AXActionData action_data;
action_data.action = ax::mojom::Action::kScrollToPoint;
action_data.target_node_id = common_ancestor_anchor->id();
action_data.target_point = target_point;
if (!common_ancestor_delegate->AccessibilityPerformAction(action_data))
return E_FAIL;
return S_OK;
}
// This function is expected to return a subset of the *direct* children of the
// common ancestor node. The subset should only include the direct children
// included - fully or partially - in the range.
HRESULT AXPlatformNodeTextRangeProviderWin::GetChildren(SAFEARRAY** children) {
UIA_VALIDATE_TEXTRANGEPROVIDER_CALL_1_OUT(children);
std::vector<gfx::NativeViewAccessible> descendants;
AXPlatformNodeWin* start_anchor =
GetPlatformNodeFromAXNode(start()->GetAnchor());
AXPlatformNodeWin* end_anchor = GetPlatformNodeFromAXNode(end()->GetAnchor());
AXPlatformNodeWin* common_anchor = GetLowestAccessibleCommonPlatformNode();
if (!common_anchor || !start_anchor || !end_anchor)
return UIA_E_ELEMENTNOTAVAILABLE;
SAFEARRAY* safe_array = SafeArrayCreateVector(VT_UNKNOWN, 0, 0);
// TODO(schectman): Implement GetUIADirectChildrenInRange for
// FlutterPlatformNodeDelegate
*children = safe_array;
return S_OK;
}
// static
bool AXPlatformNodeTextRangeProviderWin::AtStartOfLinePredicate(
const AXPositionInstance& position) {
return !position->IsIgnored() && position->AtStartOfAnchor() &&
(position->AtStartOfLine() || position->AtStartOfInlineBlock());
}
// static
bool AXPlatformNodeTextRangeProviderWin::AtEndOfLinePredicate(
const AXPositionInstance& position) {
return !position->IsIgnored() && position->AtEndOfAnchor() &&
(position->AtEndOfLine() || position->AtStartOfInlineBlock());
}
// static
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::GetNextTextBoundaryPosition(
const AXPositionInstance& position,
ax::mojom::TextBoundary boundary_type,
AXBoundaryBehavior options,
ax::mojom::MoveDirection boundary_direction) {
// Override At[Start|End]OfLinePredicate for behavior specific to UIA.
BASE_DCHECK(boundary_type != ax::mojom::TextBoundary::kNone);
switch (boundary_type) {
case ax::mojom::TextBoundary::kLineStart:
return position->CreateBoundaryStartPosition(options, boundary_direction,
&AtStartOfLinePredicate,
&AtEndOfLinePredicate);
case ax::mojom::TextBoundary::kLineEnd:
return position->CreateBoundaryEndPosition(options, boundary_direction,
&AtStartOfLinePredicate,
&AtEndOfLinePredicate);
default:
return position->CreatePositionAtTextBoundary(
boundary_type, boundary_direction, options);
}
}
std::u16string AXPlatformNodeTextRangeProviderWin::GetString(
int max_count,
size_t* appended_newlines_count) {
AXNodeRange range(start()->Clone(), end()->Clone());
return range.GetText(AXTextConcatenationBehavior::kAsTextContent, max_count,
false, appended_newlines_count);
}
AXPlatformNodeWin* AXPlatformNodeTextRangeProviderWin::GetOwner() const {
// Unit tests can't call |GetPlatformNodeFromTree|, so they must provide an
// owner node.
if (owner_for_test_.Get())
return owner_for_test_.Get();
const AXPositionInstance& position =
!start()->IsNullPosition() ? start() : end();
// If start and end are both null, there's no owner.
if (position->IsNullPosition())
return nullptr;
const AXNode* anchor = position->GetAnchor();
BASE_DCHECK(anchor);
const AXTreeManager* tree_manager =
AXTreeManagerMap::GetInstance().GetManager(anchor->tree()->GetAXTreeID());
BASE_DCHECK(tree_manager);
const AXPlatformTreeManager* platform_tree_manager =
static_cast<const AXPlatformTreeManager*>(tree_manager);
return static_cast<AXPlatformNodeWin*>(
platform_tree_manager->GetPlatformNodeFromTree(*anchor));
}
AXPlatformNodeDelegate* AXPlatformNodeTextRangeProviderWin::GetDelegate(
const AXPositionInstanceType* position) const {
return GetDelegate(position->tree_id(), position->anchor_id());
}
AXPlatformNodeDelegate* AXPlatformNodeTextRangeProviderWin::GetDelegate(
const AXTreeID tree_id,
const AXNode::AXID node_id) const {
AXPlatformNode* platform_node =
GetOwner()->GetDelegate()->GetFromTreeIDAndNodeID(tree_id, node_id);
if (!platform_node)
return nullptr;
return platform_node->GetDelegate();
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByCharacter(
const AXPositionInstance& endpoint,
const int count,
int* units_moved) {
return MoveEndpointByUnitHelper(std::move(endpoint),
ax::mojom::TextBoundary::kCharacter, count,
units_moved);
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByWord(
const AXPositionInstance& endpoint,
const int count,
int* units_moved) {
return MoveEndpointByUnitHelper(std::move(endpoint),
ax::mojom::TextBoundary::kWordStart, count,
units_moved);
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByLine(
const AXPositionInstance& endpoint,
bool is_start_endpoint,
const int count,
int* units_moved) {
return MoveEndpointByUnitHelper(std::move(endpoint),
is_start_endpoint
? ax::mojom::TextBoundary::kLineStart
: ax::mojom::TextBoundary::kLineEnd,
count, units_moved);
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByParagraph(
const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved) {
return MoveEndpointByUnitHelper(std::move(endpoint),
is_start_endpoint
? ax::mojom::TextBoundary::kParagraphStart
: ax::mojom::TextBoundary::kParagraphEnd,
count, units_moved);
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByPage(
const AXPositionInstance& endpoint,
const bool is_start_endpoint,
const int count,
int* units_moved) {
// Per UIA spec, if the document containing the current endpoint doesn't
// support pagination, default to document navigation.
//
// Note that the "ax::mojom::MoveDirection" should not matter when calculating
// the ancestor position for use when navigating by page or document, so we
// use a backward direction as the default.
AXPositionInstance common_ancestor = start()->LowestCommonAncestor(*end());
if (!common_ancestor->GetAnchor()->tree()->HasPaginationSupport())
return MoveEndpointByDocument(std::move(endpoint), count, units_moved);
return MoveEndpointByUnitHelper(std::move(endpoint),
is_start_endpoint
? ax::mojom::TextBoundary::kPageStart
: ax::mojom::TextBoundary::kPageEnd,
count, units_moved);
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByDocument(
const AXPositionInstance& endpoint,
const int count,
int* units_moved) {
BASE_DCHECK(count != 0);
if (count < 0) {
*units_moved = !endpoint->AtStartOfDocument() ? -1 : 0;
return endpoint->CreatePositionAtStartOfDocument();
}
*units_moved = !endpoint->AtEndOfDocument() ? 1 : 0;
return endpoint->CreatePositionAtEndOfDocument();
}
AXPlatformNodeTextRangeProviderWin::AXPositionInstance
AXPlatformNodeTextRangeProviderWin::MoveEndpointByUnitHelper(
const AXPositionInstance& endpoint,
const ax::mojom::TextBoundary boundary_type,
const int count,
int* units_moved) {
BASE_DCHECK(count != 0);
const ax::mojom::MoveDirection boundary_direction =
(count > 0) ? ax::mojom::MoveDirection::kForward
: ax::mojom::MoveDirection::kBackward;
const AXNode* initial_endpoint = endpoint->GetAnchor();
// Most of the methods used to create the next/previous position go back and
// forth creating a leaf text position and rooting the result to the original
// position's anchor; avoid this by normalizing to a leaf text position.
AXPositionInstance current_endpoint = endpoint->AsLeafTextPosition();
AXPositionInstance next_endpoint = GetNextTextBoundaryPosition(
current_endpoint, boundary_type,
AXBoundaryBehavior::StopAtLastAnchorBoundary, boundary_direction);
BASE_DCHECK(next_endpoint->IsLeafTextPosition());
bool is_ignored_for_text_navigation = false;
int iteration = 0;
// Since AXBoundaryBehavior::kStopAtLastAnchorBoundary forces the next
// text boundary position to be different than the input position, the
// only case where these are equal is when they're already located at the
// last anchor boundary. In such case, there is no next position to move
// to.
while (iteration < std::abs(count) &&
!(next_endpoint->GetAnchor() == current_endpoint->GetAnchor() &&
*next_endpoint == *current_endpoint)) {
is_ignored_for_text_navigation = false;
current_endpoint = std::move(next_endpoint);
next_endpoint = GetNextTextBoundaryPosition(
current_endpoint, boundary_type,
AXBoundaryBehavior::StopAtLastAnchorBoundary, boundary_direction);
BASE_DCHECK(next_endpoint->IsLeafTextPosition());
// Loop until we're not on a position that is ignored for text navigation.
// There is one exception for character navigation - since the ignored
// anchor is represented by an embedded object character, we allow
// navigation by character for consistency (i.e. you should be able to
// move by character the same number of characters that are represented by
// the ranges flat string buffer).
is_ignored_for_text_navigation =
boundary_type != ax::mojom::TextBoundary::kCharacter &&
current_endpoint->GetAnchor()->data().role !=
ax::mojom::Role::kSplitter;
if (!is_ignored_for_text_navigation)
iteration++;
}
*units_moved = (count > 0) ? iteration : -iteration;
if (is_ignored_for_text_navigation &&
initial_endpoint != current_endpoint->GetAnchor()) {
// If the last node in the tree is ignored for text navigation, we
// should still be able to return an endpoint located on that node. We
// also need to ensure that the value of |units_moved| is accurate.
*units_moved += (count > 0) ? 1 : -1;
}
return current_endpoint;
}
void AXPlatformNodeTextRangeProviderWin::NormalizeTextRange(
AXPositionInstance& start,
AXPositionInstance& end) {
if (!start->IsValid() || !end->IsValid())
return;
// If either endpoint is anchored to an ignored node,
// first snap them both to be unignored positions.
NormalizeAsUnignoredTextRange(start, end);
bool is_degenerate = *start == *end;
AXPositionInstance normalized_start =
is_degenerate ? start->Clone()
: start->AsLeafTextPositionBeforeCharacter();
// For a degenerate range, the |end_| will always be the same as the
// normalized start, so there's no need to compute the normalized end.
// However, a degenerate range might go undetected if there's an ignored node
// (or many) between the two endpoints. For this reason, we need to
// compare the |end_| with both the |start_| and the |normalized_start|.
is_degenerate = is_degenerate || *normalized_start == *end;
AXPositionInstance normalized_end =
is_degenerate ? normalized_start->Clone()
: end->AsLeafTextPositionAfterCharacter();
if (!normalized_start->IsNullPosition() &&
!normalized_end->IsNullPosition()) {
start = std::move(normalized_start);
end = std::move(normalized_end);
}
BASE_DCHECK(*start <= *end);
}
// static
void AXPlatformNodeTextRangeProviderWin::NormalizeAsUnignoredPosition(
AXPositionInstance& position) {
if (position->IsNullPosition() || !position->IsValid())
return;
if (position->IsIgnored()) {
AXPositionInstance normalized_position = position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveForward);
if (normalized_position->IsNullPosition()) {
normalized_position = position->AsUnignoredPosition(
AXPositionAdjustmentBehavior::kMoveBackward);
}
if (!normalized_position->IsNullPosition())
position = std::move(normalized_position);
}
BASE_DCHECK(!position->IsNullPosition());
}
// static
void AXPlatformNodeTextRangeProviderWin::NormalizeAsUnignoredTextRange(
AXPositionInstance& start,
AXPositionInstance& end) {
if (!start->IsValid() || !end->IsValid())
return;
if (!start->IsIgnored() && !end->IsIgnored())
return;
NormalizeAsUnignoredPosition(start);
NormalizeAsUnignoredPosition(end);
BASE_DCHECK(*start <= *end);
}
AXPlatformNodeDelegate* AXPlatformNodeTextRangeProviderWin::GetRootDelegate(
const ui::AXTreeID tree_id) {
const AXTreeManager* ax_tree_manager =
AXTreeManagerMap::GetInstance().GetManager(tree_id);
BASE_DCHECK(ax_tree_manager);
AXNode* root_node = ax_tree_manager->GetRootAsAXNode();
const AXPlatformNode* root_platform_node =
GetOwner()->GetDelegate()->GetFromTreeIDAndNodeID(tree_id,
root_node->id());
BASE_DCHECK(root_platform_node);
return root_platform_node->GetDelegate();
}
void AXPlatformNodeTextRangeProviderWin::SetStart(
AXPositionInstance new_start) {
endpoints_.SetStart(std::move(new_start));
}
void AXPlatformNodeTextRangeProviderWin::SetEnd(AXPositionInstance new_end) {
endpoints_.SetEnd(std::move(new_end));
}
void AXPlatformNodeTextRangeProviderWin::SetOwnerForTesting(
AXPlatformNodeWin* owner) {
owner_for_test_ = owner;
}
AXNode* AXPlatformNodeTextRangeProviderWin::GetSelectionCommonAnchor() {
AXPlatformNodeDelegate* delegate = GetOwner()->GetDelegate();
AXTree::Selection unignored_selection = delegate->GetUnignoredSelection();
AXPlatformNode* anchor_object =
delegate->GetFromNodeID(unignored_selection.anchor_object_id);
AXPlatformNode* focus_object =
delegate->GetFromNodeID(unignored_selection.focus_object_id);
if (!anchor_object || !focus_object)
return nullptr;
AXNodePosition::AXPositionInstance start =
anchor_object->GetDelegate()->CreateTextPositionAt(
unignored_selection.anchor_offset);
AXNodePosition::AXPositionInstance end =
focus_object->GetDelegate()->CreateTextPositionAt(
unignored_selection.focus_offset);
return start->LowestCommonAnchor(*end);
}
// When the current selection is inside a focusable element, the DOM focused
// element will correspond to this element. When we update the selection to be
// on a different element that is not focusable, the new selection won't be
// applied unless we remove the DOM focused element. For example, with Narrator,
// if we move by word from a text field (focusable) to a static text (not
// focusable), the selection will stay on the text field because the DOM focused
// element will still be the text field. To avoid that, we need to remove the
// focus from this element. Since |ax::mojom::Action::kBlur| is not implemented,
// we perform a |ax::mojom::Action::focus| action on the root node. The result
// is the same.
void AXPlatformNodeTextRangeProviderWin::
RemoveFocusFromPreviousSelectionIfNeeded(const AXNodeRange& new_selection) {
const AXNode* old_selection_node = GetSelectionCommonAnchor();
const AXNode* new_selection_node =
new_selection.anchor()->LowestCommonAnchor(*new_selection.focus());
if (!old_selection_node)
return;
if (!new_selection_node ||
(old_selection_node->data().HasState(ax::mojom::State::kFocusable) &&
!new_selection_node->data().HasState(ax::mojom::State::kFocusable))) {
AXPlatformNodeDelegate* root_delegate =
GetRootDelegate(old_selection_node->tree()->GetAXTreeID());
BASE_DCHECK(root_delegate);
AXActionData focus_action;
focus_action.action = ax::mojom::Action::kFocus;
root_delegate->AccessibilityPerformAction(focus_action);
}
}
AXPlatformNodeWin*
AXPlatformNodeTextRangeProviderWin::GetPlatformNodeFromAXNode(
const AXNode* node) const {
if (!node)
return nullptr;
// TODO(kschmi): Update to use AXTreeManager.
AXPlatformNodeWin* platform_node =
static_cast<AXPlatformNodeWin*>(AXPlatformNode::FromNativeViewAccessible(
GetDelegate(node->tree()->GetAXTreeID(), node->id())
->GetNativeViewAccessible()));
BASE_DCHECK(platform_node);
return platform_node;
}
AXPlatformNodeWin*
AXPlatformNodeTextRangeProviderWin::GetLowestAccessibleCommonPlatformNode()
const {
AXNode* common_anchor = start()->LowestCommonAnchor(*end());
if (!common_anchor)
return nullptr;
return GetPlatformNodeFromAXNode(common_anchor)->GetLowestAccessibleElement();
}
// static
bool AXPlatformNodeTextRangeProviderWin::TextAttributeIsArrayType(
TEXTATTRIBUTEID attribute_id) {
// https://docs.microsoft.com/en-us/windows/win32/winauto/uiauto-textattribute-ids
return attribute_id == UIA_AnnotationObjectsAttributeId ||
attribute_id == UIA_AnnotationTypesAttributeId ||
attribute_id == UIA_TabsAttributeId;
}
// static
bool AXPlatformNodeTextRangeProviderWin::TextAttributeIsUiaReservedValue(
const base::win::VariantVector& vector) {
// Reserved values are always IUnknown.
if (vector.Type() != VT_UNKNOWN)
return false;
base::win::ScopedVariant mixed_attribute_value_variant;
{
Microsoft::WRL::ComPtr<IUnknown> mixed_attribute_value;
HRESULT hr = ::UiaGetReservedMixedAttributeValue(&mixed_attribute_value);
BASE_DCHECK(SUCCEEDED(hr));
mixed_attribute_value_variant.Set(mixed_attribute_value.Get());
}
base::win::ScopedVariant not_supported_value_variant;
{
Microsoft::WRL::ComPtr<IUnknown> not_supported_value;
HRESULT hr = ::UiaGetReservedNotSupportedValue(¬_supported_value);
BASE_DCHECK(SUCCEEDED(hr));
not_supported_value_variant.Set(not_supported_value.Get());
}
return !vector.Compare(mixed_attribute_value_variant) ||
!vector.Compare(not_supported_value_variant);
}
// static
bool AXPlatformNodeTextRangeProviderWin::ShouldReleaseTextAttributeAsSafearray(
TEXTATTRIBUTEID attribute_id,
const base::win::VariantVector& attribute_value) {
// |vector| may be pre-populated with a UIA reserved value. In such a case, we
// must release as a scalar variant.
return TextAttributeIsArrayType(attribute_id) &&
!TextAttributeIsUiaReservedValue(attribute_value);
}
AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::TextRangeEndpoints() {
start_ = AXNodePosition::CreateNullPosition();
end_ = AXNodePosition::CreateNullPosition();
}
AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::~TextRangeEndpoints() {
SetStart(AXNodePosition::CreateNullPosition());
SetEnd(AXNodePosition::CreateNullPosition());
}
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::SetStart(
AXPositionInstance new_start) {
bool did_tree_change = start_->tree_id() != new_start->tree_id();
// TODO(bebeaudr): We can't use IsNullPosition() here because of
// https://crbug.com/1152939. Once this is fixed, we can go back to
// IsNullPosition().
if (did_tree_change && start_->kind() != AXPositionKind::NULL_POSITION &&
start_->tree_id() != end_->tree_id()) {
RemoveObserver(start_->tree_id());
}
start_ = std::move(new_start);
if (did_tree_change && !start_->IsNullPosition() &&
start_->tree_id() != end_->tree_id()) {
AddObserver(start_->tree_id());
}
}
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::SetEnd(
AXPositionInstance new_end) {
bool did_tree_change = end_->tree_id() != new_end->tree_id();
// TODO(bebeaudr): We can't use IsNullPosition() here because of
// https://crbug.com/1152939. Once this is fixed, we can go back to
// IsNullPosition().
if (did_tree_change && end_->kind() != AXPositionKind::NULL_POSITION &&
end_->tree_id() != start_->tree_id()) {
RemoveObserver(end_->tree_id());
}
end_ = std::move(new_end);
if (did_tree_change && !end_->IsNullPosition() &&
start_->tree_id() != end_->tree_id()) {
AddObserver(end_->tree_id());
}
}
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::AddObserver(
const AXTreeID tree_id) {
AXTreeManager* ax_tree_manager =
AXTreeManagerMap::GetInstance().GetManager(tree_id);
BASE_DCHECK(ax_tree_manager);
ax_tree_manager->GetTree()->AddObserver(this);
}
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::RemoveObserver(
const AXTreeID tree_id) {
AXTreeManager* ax_tree_manager =
AXTreeManagerMap::GetInstance().GetManager(tree_id);
if (ax_tree_manager)
ax_tree_manager->GetTree()->RemoveObserver(this);
}
// Ensures that our endpoints are located on non-deleted nodes (step 1, case A
// and B). See comment in header file for more details.
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::
OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) {
// If an endpoint is on a node that is included in a subtree that is about to
// be deleted, move endpoint up to the parent of the deleted subtree's root
// since we want to ensure that the endpoints of a text range provider are
// always valid positions. Otherwise, the range will be stuck on nodes that
// don't exist anymore.
BASE_DCHECK(tree);
BASE_DCHECK(node);
BASE_DCHECK(tree->GetAXTreeID() == node->tree()->GetAXTreeID());
AdjustEndpointForSubtreeDeletion(tree, node, true /* is_start_endpoint */);
AdjustEndpointForSubtreeDeletion(tree, node, false /* is_start_endpoint */);
}
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::
AdjustEndpointForSubtreeDeletion(AXTree* tree,
const AXNode* const node,
bool is_start_endpoint) {
AXPositionInstance endpoint =
is_start_endpoint ? start_->Clone() : end_->Clone();
if (tree->GetAXTreeID() != endpoint->tree_id())
return;
// When the subtree of the root node will be deleted, we can be certain that
// our endpoint should be invalidated. We know it's the root node when the
// node doesn't have a parent.
AXNode* endpoint_anchor = endpoint->GetAnchor();
if (!node->parent() || !endpoint_anchor) {
is_start_endpoint ? SetStart(AXNodePosition::CreateNullPosition())
: SetEnd(AXNodePosition::CreateNullPosition());
return;
}
DeletionOfInterest deletion_of_interest = {tree->GetAXTreeID(), node->id()};
// If the root of subtree being deleted is a child of the anchor of the
// endpoint, ensure `AXPosition::AsValidPosition` is called after the node is
// deleted so that the index doesn't go out of bounds of the child array.
if (endpoint->kind() == AXPositionKind::TREE_POSITION &&
endpoint_anchor == node->parent()) {
if (is_start_endpoint)
validation_necessary_for_start_ = deletion_of_interest;
else
validation_necessary_for_end_ = deletion_of_interest;
return;
}
// Fast check for the common case - there are many tree updates and the
// endpoints probably are not in the deleted subtree. Note that
// CreateAncestorPosition/GetParentPosition can be expensive for text
// positions.
if (!endpoint_anchor->IsDescendantOfCrossingTreeBoundary(node))
return;
AXPositionInstance new_endpoint = endpoint->CreateAncestorPosition(
node, ax::mojom::MoveDirection::kForward);
// Obviously, we want the position to be on the parent of |node| and not on
// |node| itself since it's about to be deleted.
new_endpoint = new_endpoint->CreateParentPosition();
AXPositionInstance other_endpoint =
is_start_endpoint ? end_->Clone() : start_->Clone();
// Convert |new_endpoint| and |other_endpoint| to unignored positions to avoid
// AXPosition::SlowCompareTo in the < operator below.
NormalizeAsUnignoredPosition(new_endpoint);
NormalizeAsUnignoredPosition(other_endpoint);
BASE_DCHECK(!new_endpoint->IsIgnored());
BASE_DCHECK(!other_endpoint->IsIgnored());
// If after all the above operations we're still left with a new endpoint that
// is a descendant of the subtree root being deleted, just point at a null
// position and don't crash later on. This can happen when the entire parent
// chain of the subtree is ignored.
endpoint_anchor = new_endpoint->GetAnchor();
if (!endpoint_anchor ||
endpoint_anchor->IsDescendantOfCrossingTreeBoundary(node))
new_endpoint = AXNodePosition::CreateNullPosition();
// Create a degenerate range at the new position if we have an inverted range
// - which occurs when the |end_| comes before the |start_|. This could have
// happened due to the new endpoint walking forwards or backwards when
// normalizing above. If we don't set the opposite endpoint to something that
// we know will be safe (i.e. not in a deleted subtree) we'll crash later on
// when trying to create a valid position.
if (is_start_endpoint) {
if (*other_endpoint < *new_endpoint)
SetEnd(new_endpoint->Clone());
SetStart(std::move(new_endpoint));
validation_necessary_for_start_ = deletion_of_interest;
} else {
if (*new_endpoint < *other_endpoint)
SetStart(new_endpoint->Clone());
SetEnd(std::move(new_endpoint));
validation_necessary_for_end_ = deletion_of_interest;
}
}
// Ensures that our endpoints are always valid (step 2, all scenarios). See
// comment in header file for more details.
void AXPlatformNodeTextRangeProviderWin::TextRangeEndpoints::OnNodeDeleted(
AXTree* tree,
AXNode::AXID node_id) {
BASE_DCHECK(tree);
if (validation_necessary_for_start_.has_value() &&
validation_necessary_for_start_->tree_id == tree->GetAXTreeID() &&
validation_necessary_for_start_->node_id == node_id) {
if (!start_->IsNullPosition() && start_->GetAnchor()->data().id != 0)
SetStart(start_->AsValidPosition());
else
SetStart(AXNodePosition::CreateNullPosition());
validation_necessary_for_start_ = std::nullopt;
}
if (validation_necessary_for_end_.has_value() &&
validation_necessary_for_end_->tree_id == tree->GetAXTreeID() &&
validation_necessary_for_end_->node_id == node_id) {
if (!end_->IsNullPosition() && end_->GetAnchor()->data().id != 0)
SetEnd(end_->AsValidPosition());
else
SetEnd(AXNodePosition::CreateNullPosition());
validation_necessary_for_end_ = std::nullopt;
}
}
} // namespace ui
| engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.cc/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_textrangeprovider_win.cc",
"repo_id": "engine",
"token_count": 26027
} | 449 |
// Copyright 2018 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.
#ifndef UI_ACCESSIBILITY_PLATFORM_COMPUTE_ATTRIBUTES_H_
#define UI_ACCESSIBILITY_PLATFORM_COMPUTE_ATTRIBUTES_H_
#include <cstddef>
#include <optional>
#include "ax/ax_enums.h"
#include "ax/ax_export.h"
namespace ui {
class AXPlatformNodeDelegate;
// Compute the attribute value instead of returning the "raw" attribute value
// for those attributes that have computation methods.
AX_EXPORT std::optional<int32_t> ComputeAttribute(
const ui::AXPlatformNodeDelegate* delegate,
ax::mojom::IntAttribute attribute);
} // namespace ui
#endif // UI_ACCESSIBILITY_PLATFORM_COMPUTE_ATTRIBUTES_H_
| engine/third_party/accessibility/ax/platform/compute_attributes.h/0 | {
"file_path": "engine/third_party/accessibility/ax/platform/compute_attributes.h",
"repo_id": "engine",
"token_count": 266
} | 450 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_CONTAINER_UTILS_H_
#define BASE_CONTAINER_UTILS_H_
#include <set>
#include <vector>
namespace base {
template <class T, class Allocator, class Predicate>
size_t EraseIf(std::vector<T, Allocator>& container, Predicate pred) {
auto it = std::remove_if(container.begin(), container.end(), pred);
size_t removed = std::distance(it, container.end());
container.erase(it, container.end());
return removed;
}
template <typename Container, typename Value>
bool Contains(const Container& container, const Value& value) {
return container.find(value) != container.end();
}
template <typename T>
bool Contains(const std::vector<T>& container, const T& value) {
return std::find(container.begin(), container.end(), value) !=
container.end();
}
} // namespace base
#endif // BASE_CONTAINER_UTILS_H_
| engine/third_party/accessibility/base/container_utils.h/0 | {
"file_path": "engine/third_party/accessibility/base/container_utils.h",
"repo_id": "engine",
"token_count": 321
} | 451 |
// Copyright 2014 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.
#ifndef BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
#define BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
#include <cstdint>
#include <limits>
#include <type_traits>
#if defined(__GNUC__) || defined(__clang__)
#define BASE_NUMERICS_LIKELY(x) __builtin_expect(!!(x), 1)
#define BASE_NUMERICS_UNLIKELY(x) __builtin_expect(!!(x), 0)
#else
#define BASE_NUMERICS_LIKELY(x) (x)
#define BASE_NUMERICS_UNLIKELY(x) (x)
#endif
namespace base {
namespace internal {
// The std library doesn't provide a binary max_exponent for integers, however
// we can compute an analog using std::numeric_limits<>::digits.
template <typename NumericType>
struct MaxExponent {
static const int value = std::is_floating_point<NumericType>::value
? std::numeric_limits<NumericType>::max_exponent
: std::numeric_limits<NumericType>::digits + 1;
};
// The number of bits (including the sign) in an integer. Eliminates sizeof
// hacks.
template <typename NumericType>
struct IntegerBitsPlusSign {
static const int value = std::numeric_limits<NumericType>::digits +
std::is_signed<NumericType>::value;
};
// Helper templates for integer manipulations.
template <typename Integer>
struct PositionOfSignBit {
static const size_t value = IntegerBitsPlusSign<Integer>::value - 1;
};
// Determines if a numeric value is negative without throwing compiler
// warnings on: unsigned(value) < 0.
template <typename T,
typename std::enable_if<std::is_signed<T>::value>::type* = nullptr>
constexpr bool IsValueNegative(T value) {
static_assert(std::is_arithmetic<T>::value, "Argument must be numeric.");
return value < 0;
}
template <typename T,
typename std::enable_if<!std::is_signed<T>::value>::type* = nullptr>
constexpr bool IsValueNegative(T) {
static_assert(std::is_arithmetic<T>::value, "Argument must be numeric.");
return false;
}
// This performs a fast negation, returning a signed value. It works on unsigned
// arguments, but probably doesn't do what you want for any unsigned value
// larger than max / 2 + 1 (i.e. signed min cast to unsigned).
template <typename T>
constexpr typename std::make_signed<T>::type ConditionalNegate(
T x,
bool is_negative) {
static_assert(std::is_integral<T>::value, "Type must be integral");
using SignedT = typename std::make_signed<T>::type;
using UnsignedT = typename std::make_unsigned<T>::type;
return static_cast<SignedT>(
(static_cast<UnsignedT>(x) ^ -SignedT(is_negative)) + is_negative);
}
// This performs a safe, absolute value via unsigned overflow.
template <typename T>
constexpr typename std::make_unsigned<T>::type SafeUnsignedAbs(T value) {
static_assert(std::is_integral<T>::value, "Type must be integral");
using UnsignedT = typename std::make_unsigned<T>::type;
return IsValueNegative(value)
? static_cast<UnsignedT>(0u - static_cast<UnsignedT>(value))
: static_cast<UnsignedT>(value);
}
// This allows us to switch paths on known compile-time constants.
#if defined(__clang__) || defined(__GNUC__)
constexpr bool CanDetectCompileTimeConstant() {
return true;
}
template <typename T>
constexpr bool IsCompileTimeConstant(const T v) {
return __builtin_constant_p(v);
}
#else
constexpr bool CanDetectCompileTimeConstant() {
return false;
}
template <typename T>
constexpr bool IsCompileTimeConstant(const T) {
return false;
}
#endif
template <typename T>
constexpr bool MustTreatAsConstexpr(const T v) {
// Either we can't detect a compile-time constant, and must always use the
// constexpr path, or we know we have a compile-time constant.
return !CanDetectCompileTimeConstant() || IsCompileTimeConstant(v);
}
// Forces a crash, like a CHECK(false). Used for numeric boundary errors.
// Also used in a constexpr template to trigger a compilation failure on
// an error condition.
struct CheckOnFailure {
template <typename T>
static T HandleFailure() {
#if defined(_MSC_VER)
__debugbreak();
#elif defined(__GNUC__) || defined(__clang__)
__builtin_trap();
#else
((void)(*(volatile char*)0 = 0));
#endif
return T();
}
};
enum IntegerRepresentation {
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED
};
// A range for a given nunmeric Src type is contained for a given numeric Dst
// type if both numeric_limits<Src>::max() <= numeric_limits<Dst>::max() and
// numeric_limits<Src>::lowest() >= numeric_limits<Dst>::lowest() are true.
// We implement this as template specializations rather than simple static
// comparisons to ensure type correctness in our comparisons.
enum NumericRangeRepresentation {
NUMERIC_RANGE_NOT_CONTAINED,
NUMERIC_RANGE_CONTAINED
};
// Helper templates to statically determine if our destination type can contain
// maximum and minimum values represented by the source type.
template <typename Dst,
typename Src,
IntegerRepresentation DstSign = std::is_signed<Dst>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
IntegerRepresentation SrcSign = std::is_signed<Src>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED>
struct StaticDstRangeRelationToSrcRange;
// Same sign: Dst is guaranteed to contain Src only if its range is equal or
// larger.
template <typename Dst, typename Src, IntegerRepresentation Sign>
struct StaticDstRangeRelationToSrcRange<Dst, Src, Sign, Sign> {
static const NumericRangeRepresentation value =
MaxExponent<Dst>::value >= MaxExponent<Src>::value
? NUMERIC_RANGE_CONTAINED
: NUMERIC_RANGE_NOT_CONTAINED;
};
// Unsigned to signed: Dst is guaranteed to contain source only if its range is
// larger.
template <typename Dst, typename Src>
struct StaticDstRangeRelationToSrcRange<Dst,
Src,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_UNSIGNED> {
static const NumericRangeRepresentation value =
MaxExponent<Dst>::value > MaxExponent<Src>::value
? NUMERIC_RANGE_CONTAINED
: NUMERIC_RANGE_NOT_CONTAINED;
};
// Signed to unsigned: Dst cannot be statically determined to contain Src.
template <typename Dst, typename Src>
struct StaticDstRangeRelationToSrcRange<Dst,
Src,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED> {
static const NumericRangeRepresentation value = NUMERIC_RANGE_NOT_CONTAINED;
};
// This class wraps the range constraints as separate booleans so the compiler
// can identify constants and eliminate unused code paths.
class RangeCheck {
public:
constexpr RangeCheck(bool is_in_lower_bound, bool is_in_upper_bound)
: is_underflow_(!is_in_lower_bound), is_overflow_(!is_in_upper_bound) {}
constexpr RangeCheck() : is_underflow_(0), is_overflow_(0) {}
constexpr bool IsValid() const { return !is_overflow_ && !is_underflow_; }
constexpr bool IsInvalid() const { return is_overflow_ && is_underflow_; }
constexpr bool IsOverflow() const { return is_overflow_ && !is_underflow_; }
constexpr bool IsUnderflow() const { return !is_overflow_ && is_underflow_; }
constexpr bool IsOverflowFlagSet() const { return is_overflow_; }
constexpr bool IsUnderflowFlagSet() const { return is_underflow_; }
constexpr bool operator==(const RangeCheck rhs) const {
return is_underflow_ == rhs.is_underflow_ &&
is_overflow_ == rhs.is_overflow_;
}
constexpr bool operator!=(const RangeCheck rhs) const {
return !(*this == rhs);
}
private:
// Do not change the order of these member variables. The integral conversion
// optimization depends on this exact order.
const bool is_underflow_;
const bool is_overflow_;
};
// The following helper template addresses a corner case in range checks for
// conversion from a floating-point type to an integral type of smaller range
// but larger precision (e.g. float -> unsigned). The problem is as follows:
// 1. Integral maximum is always one less than a power of two, so it must be
// truncated to fit the mantissa of the floating point. The direction of
// rounding is implementation defined, but by default it's always IEEE
// floats, which round to nearest and thus result in a value of larger
// magnitude than the integral value.
// Example: float f = UINT_MAX; // f is 4294967296f but UINT_MAX
// // is 4294967295u.
// 2. If the floating point value is equal to the promoted integral maximum
// value, a range check will erroneously pass.
// Example: (4294967296f <= 4294967295u) // This is true due to a precision
// // loss in rounding up to float.
// 3. When the floating point value is then converted to an integral, the
// resulting value is out of range for the target integral type and
// thus is implementation defined.
// Example: unsigned u = (float)INT_MAX; // u will typically overflow to 0.
// To fix this bug we manually truncate the maximum value when the destination
// type is an integral of larger precision than the source floating-point type,
// such that the resulting maximum is represented exactly as a floating point.
template <typename Dst, typename Src, template <typename> class Bounds>
struct NarrowingRange {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = typename std::numeric_limits<Dst>;
// Computes the mask required to make an accurate comparison between types.
static const int kShift =
(MaxExponent<Src>::value > MaxExponent<Dst>::value &&
SrcLimits::digits < DstLimits::digits)
? (DstLimits::digits - SrcLimits::digits)
: 0;
template <
typename T,
typename std::enable_if<std::is_integral<T>::value>::type* = nullptr>
// Masks out the integer bits that are beyond the precision of the
// intermediate type used for comparison.
static constexpr T Adjust(T value) {
static_assert(std::is_same<T, Dst>::value, "");
static_assert(kShift < DstLimits::digits, "");
return static_cast<T>(
ConditionalNegate(SafeUnsignedAbs(value) & ~((T(1) << kShift) - T(1)),
IsValueNegative(value)));
}
template <typename T,
typename std::enable_if<std::is_floating_point<T>::value>::type* =
nullptr>
static constexpr T Adjust(T value) {
static_assert(std::is_same<T, Dst>::value, "");
static_assert(kShift == 0, "");
return value;
}
static constexpr Dst max() { return Adjust(Bounds<Dst>::max()); }
static constexpr Dst lowest() { return Adjust(Bounds<Dst>::lowest()); }
};
template <typename Dst,
typename Src,
template <typename>
class Bounds,
IntegerRepresentation DstSign = std::is_signed<Dst>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
IntegerRepresentation SrcSign = std::is_signed<Src>::value
? INTEGER_REPRESENTATION_SIGNED
: INTEGER_REPRESENTATION_UNSIGNED,
NumericRangeRepresentation DstRange =
StaticDstRangeRelationToSrcRange<Dst, Src>::value>
struct DstRangeRelationToSrcRangeImpl;
// The following templates are for ranges that must be verified at runtime. We
// split it into checks based on signedness to avoid confusing casts and
// compiler warnings on signed an unsigned comparisons.
// Same sign narrowing: The range is contained for normal limits.
template <typename Dst,
typename Src,
template <typename>
class Bounds,
IntegerRepresentation DstSign,
IntegerRepresentation SrcSign>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
DstSign,
SrcSign,
NUMERIC_RANGE_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(
static_cast<Dst>(SrcLimits::lowest()) >= DstLimits::lowest() ||
static_cast<Dst>(value) >= DstLimits::lowest(),
static_cast<Dst>(SrcLimits::max()) <= DstLimits::max() ||
static_cast<Dst>(value) <= DstLimits::max());
}
};
// Signed to signed narrowing: Both the upper and lower boundaries may be
// exceeded for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_SIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(value >= DstLimits::lowest(), value <= DstLimits::max());
}
};
// Unsigned to unsigned narrowing: Only the upper bound can be exceeded for
// standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_UNSIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
return RangeCheck(
DstLimits::lowest() == Dst(0) || value >= DstLimits::lowest(),
value <= DstLimits::max());
}
};
// Unsigned to signed: Only the upper bound can be exceeded for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_SIGNED,
INTEGER_REPRESENTATION_UNSIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
using Promotion = decltype(Src() + Dst());
return RangeCheck(DstLimits::lowest() <= Dst(0) ||
static_cast<Promotion>(value) >=
static_cast<Promotion>(DstLimits::lowest()),
static_cast<Promotion>(value) <=
static_cast<Promotion>(DstLimits::max()));
}
};
// Signed to unsigned: The upper boundary may be exceeded for a narrower Dst,
// and any negative value exceeds the lower boundary for standard limits.
template <typename Dst, typename Src, template <typename> class Bounds>
struct DstRangeRelationToSrcRangeImpl<Dst,
Src,
Bounds,
INTEGER_REPRESENTATION_UNSIGNED,
INTEGER_REPRESENTATION_SIGNED,
NUMERIC_RANGE_NOT_CONTAINED> {
static constexpr RangeCheck Check(Src value) {
using SrcLimits = std::numeric_limits<Src>;
using DstLimits = NarrowingRange<Dst, Src, Bounds>;
using Promotion = decltype(Src() + Dst());
return RangeCheck(
value >= Src(0) && (DstLimits::lowest() == 0 ||
static_cast<Dst>(value) >= DstLimits::lowest()),
static_cast<Promotion>(SrcLimits::max()) <=
static_cast<Promotion>(DstLimits::max()) ||
static_cast<Promotion>(value) <=
static_cast<Promotion>(DstLimits::max()));
}
};
// Simple wrapper for statically checking if a type's range is contained.
template <typename Dst, typename Src>
struct IsTypeInRangeForNumericType {
static const bool value = StaticDstRangeRelationToSrcRange<Dst, Src>::value ==
NUMERIC_RANGE_CONTAINED;
};
template <typename Dst,
template <typename> class Bounds = std::numeric_limits,
typename Src>
constexpr RangeCheck DstRangeRelationToSrcRange(Src value) {
static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric.");
static_assert(std::is_arithmetic<Dst>::value, "Result must be numeric.");
static_assert(Bounds<Dst>::lowest() < Bounds<Dst>::max(), "");
return DstRangeRelationToSrcRangeImpl<Dst, Src, Bounds>::Check(value);
}
// Integer promotion templates used by the portable checked integer arithmetic.
template <size_t Size, bool IsSigned>
struct IntegerForDigitsAndSign;
#define INTEGER_FOR_DIGITS_AND_SIGN(I) \
template <> \
struct IntegerForDigitsAndSign<IntegerBitsPlusSign<I>::value, \
std::is_signed<I>::value> { \
using type = I; \
}
INTEGER_FOR_DIGITS_AND_SIGN(int8_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint8_t);
INTEGER_FOR_DIGITS_AND_SIGN(int16_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint16_t);
INTEGER_FOR_DIGITS_AND_SIGN(int32_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint32_t);
INTEGER_FOR_DIGITS_AND_SIGN(int64_t);
INTEGER_FOR_DIGITS_AND_SIGN(uint64_t);
#undef INTEGER_FOR_DIGITS_AND_SIGN
// WARNING: We have no IntegerForSizeAndSign<16, *>. If we ever add one to
// support 128-bit math, then the ArithmeticPromotion template below will need
// to be updated (or more likely replaced with a decltype expression).
static_assert(IntegerBitsPlusSign<intmax_t>::value == 64,
"Max integer size not supported for this toolchain.");
template <typename Integer, bool IsSigned = std::is_signed<Integer>::value>
struct TwiceWiderInteger {
using type =
typename IntegerForDigitsAndSign<IntegerBitsPlusSign<Integer>::value * 2,
IsSigned>::type;
};
enum ArithmeticPromotionCategory {
LEFT_PROMOTION, // Use the type of the left-hand argument.
RIGHT_PROMOTION // Use the type of the right-hand argument.
};
// Determines the type that can represent the largest positive value.
template <typename Lhs,
typename Rhs,
ArithmeticPromotionCategory Promotion =
(MaxExponent<Lhs>::value > MaxExponent<Rhs>::value)
? LEFT_PROMOTION
: RIGHT_PROMOTION>
struct MaxExponentPromotion;
template <typename Lhs, typename Rhs>
struct MaxExponentPromotion<Lhs, Rhs, LEFT_PROMOTION> {
using type = Lhs;
};
template <typename Lhs, typename Rhs>
struct MaxExponentPromotion<Lhs, Rhs, RIGHT_PROMOTION> {
using type = Rhs;
};
// Determines the type that can represent the lowest arithmetic value.
template <typename Lhs,
typename Rhs,
ArithmeticPromotionCategory Promotion =
std::is_signed<Lhs>::value
? (std::is_signed<Rhs>::value
? (MaxExponent<Lhs>::value > MaxExponent<Rhs>::value
? LEFT_PROMOTION
: RIGHT_PROMOTION)
: LEFT_PROMOTION)
: (std::is_signed<Rhs>::value
? RIGHT_PROMOTION
: (MaxExponent<Lhs>::value < MaxExponent<Rhs>::value
? LEFT_PROMOTION
: RIGHT_PROMOTION))>
struct LowestValuePromotion;
template <typename Lhs, typename Rhs>
struct LowestValuePromotion<Lhs, Rhs, LEFT_PROMOTION> {
using type = Lhs;
};
template <typename Lhs, typename Rhs>
struct LowestValuePromotion<Lhs, Rhs, RIGHT_PROMOTION> {
using type = Rhs;
};
// Determines the type that is best able to represent an arithmetic result.
template <
typename Lhs,
typename Rhs = Lhs,
bool is_intmax_type =
std::is_integral<typename MaxExponentPromotion<Lhs, Rhs>::type>::value&&
IntegerBitsPlusSign<typename MaxExponentPromotion<Lhs, Rhs>::type>::
value == IntegerBitsPlusSign<intmax_t>::value,
bool is_max_exponent =
StaticDstRangeRelationToSrcRange<
typename MaxExponentPromotion<Lhs, Rhs>::type,
Lhs>::value ==
NUMERIC_RANGE_CONTAINED&& StaticDstRangeRelationToSrcRange<
typename MaxExponentPromotion<Lhs, Rhs>::type,
Rhs>::value == NUMERIC_RANGE_CONTAINED>
struct BigEnoughPromotion;
// The side with the max exponent is big enough.
template <typename Lhs, typename Rhs, bool is_intmax_type>
struct BigEnoughPromotion<Lhs, Rhs, is_intmax_type, true> {
using type = typename MaxExponentPromotion<Lhs, Rhs>::type;
static const bool is_contained = true;
};
// We can use a twice wider type to fit.
template <typename Lhs, typename Rhs>
struct BigEnoughPromotion<Lhs, Rhs, false, false> {
using type =
typename TwiceWiderInteger<typename MaxExponentPromotion<Lhs, Rhs>::type,
std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value>::type;
static const bool is_contained = true;
};
// No type is large enough.
template <typename Lhs, typename Rhs>
struct BigEnoughPromotion<Lhs, Rhs, true, false> {
using type = typename MaxExponentPromotion<Lhs, Rhs>::type;
static const bool is_contained = false;
};
// We can statically check if operations on the provided types can wrap, so we
// can skip the checked operations if they're not needed. So, for an integer we
// care if the destination type preserves the sign and is twice the width of
// the source.
template <typename T, typename Lhs, typename Rhs = Lhs>
struct IsIntegerArithmeticSafe {
static const bool value =
!std::is_floating_point<T>::value &&
!std::is_floating_point<Lhs>::value &&
!std::is_floating_point<Rhs>::value &&
std::is_signed<T>::value >= std::is_signed<Lhs>::value &&
IntegerBitsPlusSign<T>::value >= (2 * IntegerBitsPlusSign<Lhs>::value) &&
std::is_signed<T>::value >= std::is_signed<Rhs>::value &&
IntegerBitsPlusSign<T>::value >= (2 * IntegerBitsPlusSign<Rhs>::value);
};
// Promotes to a type that can represent any possible result of a binary
// arithmetic operation with the source types.
template <typename Lhs,
typename Rhs,
bool is_promotion_possible = IsIntegerArithmeticSafe<
typename std::conditional<std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value,
intmax_t,
uintmax_t>::type,
typename MaxExponentPromotion<Lhs, Rhs>::type>::value>
struct FastIntegerArithmeticPromotion;
template <typename Lhs, typename Rhs>
struct FastIntegerArithmeticPromotion<Lhs, Rhs, true> {
using type =
typename TwiceWiderInteger<typename MaxExponentPromotion<Lhs, Rhs>::type,
std::is_signed<Lhs>::value ||
std::is_signed<Rhs>::value>::type;
static_assert(IsIntegerArithmeticSafe<type, Lhs, Rhs>::value, "");
static const bool is_contained = true;
};
template <typename Lhs, typename Rhs>
struct FastIntegerArithmeticPromotion<Lhs, Rhs, false> {
using type = typename BigEnoughPromotion<Lhs, Rhs>::type;
static const bool is_contained = false;
};
// Extracts the underlying type from an enum.
template <typename T, bool is_enum = std::is_enum<T>::value>
struct ArithmeticOrUnderlyingEnum;
template <typename T>
struct ArithmeticOrUnderlyingEnum<T, true> {
using type = typename std::underlying_type<T>::type;
static const bool value = std::is_arithmetic<type>::value;
};
template <typename T>
struct ArithmeticOrUnderlyingEnum<T, false> {
using type = T;
static const bool value = std::is_arithmetic<type>::value;
};
// The following are helper templates used in the CheckedNumeric class.
template <typename T>
class CheckedNumeric;
template <typename T>
class ClampedNumeric;
template <typename T>
class StrictNumeric;
// Used to treat CheckedNumeric and arithmetic underlying types the same.
template <typename T>
struct UnderlyingType {
using type = typename ArithmeticOrUnderlyingEnum<T>::type;
static const bool is_numeric = std::is_arithmetic<type>::value;
static const bool is_checked = false;
static const bool is_clamped = false;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<CheckedNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = true;
static const bool is_clamped = false;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<ClampedNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = false;
static const bool is_clamped = true;
static const bool is_strict = false;
};
template <typename T>
struct UnderlyingType<StrictNumeric<T>> {
using type = T;
static const bool is_numeric = true;
static const bool is_checked = false;
static const bool is_clamped = false;
static const bool is_strict = true;
};
template <typename L, typename R>
struct IsCheckedOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked);
};
template <typename L, typename R>
struct IsClampedOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_clamped || UnderlyingType<R>::is_clamped) &&
!(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked);
};
template <typename L, typename R>
struct IsStrictOp {
static const bool value =
UnderlyingType<L>::is_numeric && UnderlyingType<R>::is_numeric &&
(UnderlyingType<L>::is_strict || UnderlyingType<R>::is_strict) &&
!(UnderlyingType<L>::is_checked || UnderlyingType<R>::is_checked) &&
!(UnderlyingType<L>::is_clamped || UnderlyingType<R>::is_clamped);
};
// as_signed<> returns the supplied integral value (or integral castable
// Numeric template) cast as a signed integral of equivalent precision.
// I.e. it's mostly an alias for: static_cast<std::make_signed<T>::type>(t)
template <typename Src>
constexpr typename std::make_signed<
typename base::internal::UnderlyingType<Src>::type>::type
as_signed(const Src value) {
static_assert(std::is_integral<decltype(as_signed(value))>::value,
"Argument must be a signed or unsigned integer type.");
return static_cast<decltype(as_signed(value))>(value);
}
// as_unsigned<> returns the supplied integral value (or integral castable
// Numeric template) cast as an unsigned integral of equivalent precision.
// I.e. it's mostly an alias for: static_cast<std::make_unsigned<T>::type>(t)
template <typename Src>
constexpr typename std::make_unsigned<
typename base::internal::UnderlyingType<Src>::type>::type
as_unsigned(const Src value) {
static_assert(std::is_integral<decltype(as_unsigned(value))>::value,
"Argument must be a signed or unsigned integer type.");
return static_cast<decltype(as_unsigned(value))>(value);
}
template <typename L, typename R>
constexpr bool IsLessImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsUnderflow() || r_range.IsOverflow() ||
(l_range == r_range && static_cast<decltype(lhs + rhs)>(lhs) <
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsLess {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsLessImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsLessOrEqualImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsUnderflow() || r_range.IsOverflow() ||
(l_range == r_range && static_cast<decltype(lhs + rhs)>(lhs) <=
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsLessOrEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsLessOrEqualImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsGreaterImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsOverflow() || r_range.IsUnderflow() ||
(l_range == r_range && static_cast<decltype(lhs + rhs)>(lhs) >
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsGreater {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsGreaterImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
constexpr bool IsGreaterOrEqualImpl(const L lhs,
const R rhs,
const RangeCheck l_range,
const RangeCheck r_range) {
return l_range.IsOverflow() || r_range.IsUnderflow() ||
(l_range == r_range && static_cast<decltype(lhs + rhs)>(lhs) >=
static_cast<decltype(lhs + rhs)>(rhs));
}
template <typename L, typename R>
struct IsGreaterOrEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return IsGreaterOrEqualImpl(lhs, rhs, DstRangeRelationToSrcRange<R>(lhs),
DstRangeRelationToSrcRange<L>(rhs));
}
};
template <typename L, typename R>
struct IsEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return DstRangeRelationToSrcRange<R>(lhs) ==
DstRangeRelationToSrcRange<L>(rhs) &&
static_cast<decltype(lhs + rhs)>(lhs) ==
static_cast<decltype(lhs + rhs)>(rhs);
}
};
template <typename L, typename R>
struct IsNotEqual {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
static constexpr bool Test(const L lhs, const R rhs) {
return DstRangeRelationToSrcRange<R>(lhs) !=
DstRangeRelationToSrcRange<L>(rhs) ||
static_cast<decltype(lhs + rhs)>(lhs) !=
static_cast<decltype(lhs + rhs)>(rhs);
}
};
// These perform the actual math operations on the CheckedNumerics.
// Binary arithmetic operations.
template <template <typename, typename> class C, typename L, typename R>
constexpr bool SafeCompare(const L lhs, const R rhs) {
static_assert(std::is_arithmetic<L>::value && std::is_arithmetic<R>::value,
"Types must be numeric.");
using Promotion = BigEnoughPromotion<L, R>;
using BigType = typename Promotion::type;
return Promotion::is_contained
// Force to a larger type for speed if both are contained.
? C<BigType, BigType>::Test(
static_cast<BigType>(static_cast<L>(lhs)),
static_cast<BigType>(static_cast<R>(rhs)))
// Let the template functions figure it out for mixed types.
: C<L, R>::Test(lhs, rhs);
}
template <typename Dst, typename Src>
constexpr bool IsMaxInRangeForNumericType() {
return IsGreaterOrEqual<Dst, Src>::Test(std::numeric_limits<Dst>::max(),
std::numeric_limits<Src>::max());
}
template <typename Dst, typename Src>
constexpr bool IsMinInRangeForNumericType() {
return IsLessOrEqual<Dst, Src>::Test(std::numeric_limits<Dst>::lowest(),
std::numeric_limits<Src>::lowest());
}
template <typename Dst, typename Src>
constexpr Dst CommonMax() {
return !IsMaxInRangeForNumericType<Dst, Src>()
? Dst(std::numeric_limits<Dst>::max())
: Dst(std::numeric_limits<Src>::max());
}
template <typename Dst, typename Src>
constexpr Dst CommonMin() {
return !IsMinInRangeForNumericType<Dst, Src>()
? Dst(std::numeric_limits<Dst>::lowest())
: Dst(std::numeric_limits<Src>::lowest());
}
// This is a wrapper to generate return the max or min for a supplied type.
// If the argument is false, the returned value is the maximum. If true the
// returned value is the minimum.
template <typename Dst, typename Src = Dst>
constexpr Dst CommonMaxOrMin(bool is_min) {
return is_min ? CommonMin<Dst, Src>() : CommonMax<Dst, Src>();
}
} // namespace internal
} // namespace base
#endif // BASE_NUMERICS_SAFE_CONVERSIONS_IMPL_H_
| engine/third_party/accessibility/base/numerics/safe_conversions_impl.h/0 | {
"file_path": "engine/third_party/accessibility/base/numerics/safe_conversions_impl.h",
"repo_id": "engine",
"token_count": 14766
} | 452 |
// Copyright 2020 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.
#ifndef BASE_WIN_DISPATCH_STUB_H_
#define BASE_WIN_DISPATCH_STUB_H_
#include <wrl/client.h>
#include <wrl/implements.h>
namespace base {
namespace win {
namespace test {
// An unimplemented IDispatch subclass for testing purposes.
class DispatchStub
: public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>,
IDispatch> {
public:
DispatchStub() = default;
DispatchStub(const DispatchStub&) = delete;
DispatchStub& operator=(const DispatchStub&) = delete;
// IDispatch:
IFACEMETHODIMP GetTypeInfoCount(UINT*) override;
IFACEMETHODIMP GetTypeInfo(UINT, LCID, ITypeInfo**) override;
IFACEMETHODIMP GetIDsOfNames(REFIID, LPOLESTR*, UINT, LCID, DISPID*) override;
IFACEMETHODIMP Invoke(DISPID,
REFIID,
LCID,
WORD,
DISPPARAMS*,
VARIANT*,
EXCEPINFO*,
UINT*) override;
};
} // namespace test
} // namespace win
} // namespace base
#endif // BASE_WIN_DISPATCH_STUB_H_
| engine/third_party/accessibility/base/win/dispatch_stub.h/0 | {
"file_path": "engine/third_party/accessibility/base/win/dispatch_stub.h",
"repo_id": "engine",
"token_count": 573
} | 453 |
// Copyright 2020 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.
#include "base/win/variant_vector.h"
#include "base/win/scoped_safearray.h"
#include "base/win/scoped_variant.h"
namespace base {
namespace win {
namespace {
// Lexicographical comparison between the contents of |vector| and |safearray|.
template <VARTYPE ElementVartype>
int CompareAgainstSafearray(const std::vector<ScopedVariant>& vector,
const ScopedSafearray& safearray,
bool ignore_case) {
std::optional<ScopedSafearray::LockScope<ElementVartype>> lock_scope =
safearray.CreateLockScope<ElementVartype>();
// If we fail to create a lock scope, then arbitrarily treat |this| as
// greater. This should only happen when the SAFEARRAY fails to be locked,
// so we cannot compare the contents of the SAFEARRAY.
if (!lock_scope)
return 1;
// Create a temporary VARIANT which does not own its contents, and is
// populated with values from the |lock_scope| so it can be compared against.
VARIANT non_owning_temp;
V_VT(&non_owning_temp) = ElementVartype;
auto vector_iter = vector.begin();
auto scope_iter = lock_scope->begin();
for (; vector_iter != vector.end() && scope_iter != lock_scope->end();
++vector_iter, ++scope_iter) {
internal::VariantUtil<ElementVartype>::RawSet(&non_owning_temp,
*scope_iter);
int compare_result = vector_iter->Compare(non_owning_temp, ignore_case);
// If there is a difference in values, return the difference.
if (compare_result)
return compare_result;
}
// There are more elements in |vector|, so |vector| is
// greater than |safearray|.
if (vector_iter != vector.end())
return 1;
// There are more elements in |safearray|, so |vector| is
// less than |safearray|.
if (scope_iter != lock_scope->end())
return -1;
return 0;
}
} // namespace
VariantVector::VariantVector() = default;
VariantVector::VariantVector(VariantVector&& other)
: vartype_(std::exchange(other.vartype_, VT_EMPTY)),
vector_(std::move(other.vector_)) {}
VariantVector& VariantVector::operator=(VariantVector&& other) {
BASE_DCHECK(this != &other);
vartype_ = std::exchange(other.vartype_, VT_EMPTY);
vector_ = std::move(other.vector_);
return *this;
}
VariantVector::~VariantVector() {
Reset();
}
bool VariantVector::operator==(const VariantVector& other) const {
return !Compare(other);
}
bool VariantVector::operator!=(const VariantVector& other) const {
return !VariantVector::operator==(other);
}
void VariantVector::Reset() {
vector_.clear();
vartype_ = VT_EMPTY;
}
VARIANT VariantVector::ReleaseAsScalarVariant() {
ScopedVariant scoped_variant;
if (!Empty()) {
BASE_DCHECK(Size() == 1U);
scoped_variant = std::move(vector_[0]);
Reset();
}
return scoped_variant.Release();
}
VARIANT VariantVector::ReleaseAsSafearrayVariant() {
ScopedVariant scoped_variant;
switch (Type()) {
case VT_EMPTY:
break;
case VT_BOOL:
scoped_variant.Set(CreateAndPopulateSafearray<VT_BOOL>());
break;
case VT_I1:
scoped_variant.Set(CreateAndPopulateSafearray<VT_I1>());
break;
case VT_UI1:
scoped_variant.Set(CreateAndPopulateSafearray<VT_UI1>());
break;
case VT_I2:
scoped_variant.Set(CreateAndPopulateSafearray<VT_I2>());
break;
case VT_UI2:
scoped_variant.Set(CreateAndPopulateSafearray<VT_UI2>());
break;
case VT_I4:
scoped_variant.Set(CreateAndPopulateSafearray<VT_I4>());
break;
case VT_UI4:
scoped_variant.Set(CreateAndPopulateSafearray<VT_UI4>());
break;
case VT_I8:
scoped_variant.Set(CreateAndPopulateSafearray<VT_I8>());
break;
case VT_UI8:
scoped_variant.Set(CreateAndPopulateSafearray<VT_UI8>());
break;
case VT_R4:
scoped_variant.Set(CreateAndPopulateSafearray<VT_R4>());
break;
case VT_R8:
scoped_variant.Set(CreateAndPopulateSafearray<VT_R8>());
break;
case VT_DATE:
scoped_variant.Set(CreateAndPopulateSafearray<VT_DATE>());
break;
case VT_BSTR:
scoped_variant.Set(CreateAndPopulateSafearray<VT_BSTR>());
break;
case VT_DISPATCH:
scoped_variant.Set(CreateAndPopulateSafearray<VT_DISPATCH>());
break;
case VT_UNKNOWN:
scoped_variant.Set(CreateAndPopulateSafearray<VT_UNKNOWN>());
break;
// The default case shouldn't be reachable, but if we added support for more
// VARTYPEs to base::win::internal::VariantUtil<> and they were inserted
// into a VariantVector then it would be possible to reach the default case
// for those new types until implemented.
//
// Because the switch is against VARTYPE (unsigned short) and not VARENUM,
// removing the default case will not result in build warnings/errors if
// there are missing cases. It is important that this uses VARTYPE rather
// than VARENUM, because in the future we may want to support complex
// VARTYPES. For example a value within VT_TYPEMASK that's joined something
// outside the typemask like VT_ARRAY or VT_BYREF.
default:
BASE_UNREACHABLE();
break;
}
// CreateAndPopulateSafearray handles resetting |this| to VT_EMPTY because it
// transfers ownership of each element to the SAFEARRAY.
return scoped_variant.Release();
}
int VariantVector::Compare(const VARIANT& other, bool ignore_case) const {
// If the element variant types are different, compare against the types.
if (Type() != (V_VT(&other) & VT_TYPEMASK))
return (Type() < (V_VT(&other) & VT_TYPEMASK)) ? (-1) : 1;
// Both have an empty variant type so they are the same.
if (Type() == VT_EMPTY)
return 0;
int compare_result = 0;
if (V_ISARRAY(&other)) {
compare_result = Compare(V_ARRAY(&other), ignore_case);
} else {
compare_result = vector_[0].Compare(other, ignore_case);
// If the first element is equal to |other|, and |vector_|
// has more than one element, then |vector_| is greater.
if (!compare_result && Size() > 1)
compare_result = 1;
}
return compare_result;
}
int VariantVector::Compare(const VariantVector& other, bool ignore_case) const {
// If the element variant types are different, compare against the types.
if (Type() != other.Type())
return (Type() < other.Type()) ? (-1) : 1;
// Both have an empty variant type so they are the same.
if (Type() == VT_EMPTY)
return 0;
auto iter1 = vector_.begin();
auto iter2 = other.vector_.begin();
for (; (iter1 != vector_.end()) && (iter2 != other.vector_.end());
++iter1, ++iter2) {
int compare_result = iter1->Compare(*iter2, ignore_case);
if (compare_result)
return compare_result;
}
// There are more elements in |this|, so |this| is greater than |other|.
if (iter1 != vector_.end())
return 1;
// There are more elements in |other|, so |this| is less than |other|.
if (iter2 != other.vector_.end())
return -1;
return 0;
}
int VariantVector::Compare(SAFEARRAY* safearray, bool ignore_case) const {
VARTYPE safearray_vartype;
// If we fail to get the element variant type for the SAFEARRAY, then
// arbitrarily treat |this| as greater.
if (FAILED(SafeArrayGetVartype(safearray, &safearray_vartype)))
return 1;
// If the element variant types are different, compare against the types.
if (Type() != safearray_vartype)
return (Type() < safearray_vartype) ? (-1) : 1;
ScopedSafearray scoped_safearray(safearray);
int compare_result = 0;
switch (Type()) {
case VT_BOOL:
compare_result = CompareAgainstSafearray<VT_BOOL>(
vector_, scoped_safearray, ignore_case);
break;
case VT_I1:
compare_result = CompareAgainstSafearray<VT_I1>(vector_, scoped_safearray,
ignore_case);
break;
case VT_UI1:
compare_result = CompareAgainstSafearray<VT_UI1>(
vector_, scoped_safearray, ignore_case);
break;
case VT_I2:
compare_result = CompareAgainstSafearray<VT_I2>(vector_, scoped_safearray,
ignore_case);
break;
case VT_UI2:
compare_result = CompareAgainstSafearray<VT_UI2>(
vector_, scoped_safearray, ignore_case);
break;
case VT_I4:
compare_result = CompareAgainstSafearray<VT_I4>(vector_, scoped_safearray,
ignore_case);
break;
case VT_UI4:
compare_result = CompareAgainstSafearray<VT_UI4>(
vector_, scoped_safearray, ignore_case);
break;
case VT_I8:
compare_result = CompareAgainstSafearray<VT_I8>(vector_, scoped_safearray,
ignore_case);
break;
case VT_UI8:
compare_result = CompareAgainstSafearray<VT_UI8>(
vector_, scoped_safearray, ignore_case);
break;
case VT_R4:
compare_result = CompareAgainstSafearray<VT_R4>(vector_, scoped_safearray,
ignore_case);
break;
case VT_R8:
compare_result = CompareAgainstSafearray<VT_R8>(vector_, scoped_safearray,
ignore_case);
break;
case VT_DATE:
compare_result = CompareAgainstSafearray<VT_DATE>(
vector_, scoped_safearray, ignore_case);
break;
case VT_BSTR:
compare_result = CompareAgainstSafearray<VT_BSTR>(
vector_, scoped_safearray, ignore_case);
break;
case VT_DISPATCH:
compare_result = CompareAgainstSafearray<VT_DISPATCH>(
vector_, scoped_safearray, ignore_case);
break;
case VT_UNKNOWN:
compare_result = CompareAgainstSafearray<VT_UNKNOWN>(
vector_, scoped_safearray, ignore_case);
break;
// The default case shouldn't be reachable, but if we added support for more
// VARTYPEs to base::win::internal::VariantUtil<> and they were inserted
// into a VariantVector then it would be possible to reach the default case
// for those new types until implemented.
//
// Because the switch is against VARTYPE (unsigned short) and not VARENUM,
// removing the default case will not result in build warnings/errors if
// there are missing cases. It is important that this uses VARTYPE rather
// than VARENUM, because in the future we may want to support complex
// VARTYPES. For example a value within VT_TYPEMASK that's joined something
// outside the typemask like VT_ARRAY or VT_BYREF.
default:
compare_result = 1;
BASE_UNREACHABLE();
break;
}
scoped_safearray.Release();
return compare_result;
}
template <VARTYPE ElementVartype>
SAFEARRAY* VariantVector::CreateAndPopulateSafearray() {
BASE_DCHECK(!Empty());
ScopedSafearray scoped_safearray(
SafeArrayCreateVector(ElementVartype, 0, Size()));
if (!scoped_safearray.Get()) {
constexpr size_t kElementSize =
sizeof(typename internal::VariantUtil<ElementVartype>::Type);
std::abort();
}
std::optional<ScopedSafearray::LockScope<ElementVartype>> lock_scope =
scoped_safearray.CreateLockScope<ElementVartype>();
BASE_DCHECK(lock_scope);
for (size_t i = 0; i < Size(); ++i) {
VARIANT element = vector_[i].Release();
(*lock_scope)[i] = internal::VariantUtil<ElementVartype>::RawGet(element);
}
Reset();
return scoped_safearray.Release();
}
} // namespace win
} // namespace base
| engine/third_party/accessibility/base/win/variant_vector.cc/0 | {
"file_path": "engine/third_party/accessibility/base/win/variant_vector.cc",
"repo_id": "engine",
"token_count": 4731
} | 454 |
// Copyright (c) 2012 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.
#include <cstddef>
#include "gtest/gtest.h"
#include "point.h"
#include "point_conversions.h"
#include "point_f.h"
namespace gfx {
TEST(PointTest, ToPointF) {
// Check that explicit conversion from integer to float compiles.
Point a(10, 20);
PointF b = PointF(a);
EXPECT_EQ(static_cast<float>(a.x()), b.x());
EXPECT_EQ(static_cast<float>(a.y()), b.y());
}
TEST(PointTest, IsOrigin) {
EXPECT_FALSE(Point(1, 0).IsOrigin());
EXPECT_FALSE(Point(0, 1).IsOrigin());
EXPECT_FALSE(Point(1, 2).IsOrigin());
EXPECT_FALSE(Point(-1, 0).IsOrigin());
EXPECT_FALSE(Point(0, -1).IsOrigin());
EXPECT_FALSE(Point(-1, -2).IsOrigin());
EXPECT_TRUE(Point(0, 0).IsOrigin());
EXPECT_FALSE(PointF(0.1f, 0).IsOrigin());
EXPECT_FALSE(PointF(0, 0.1f).IsOrigin());
EXPECT_FALSE(PointF(0.1f, 2).IsOrigin());
EXPECT_FALSE(PointF(-0.1f, 0).IsOrigin());
EXPECT_FALSE(PointF(0, -0.1f).IsOrigin());
EXPECT_FALSE(PointF(-0.1f, -2).IsOrigin());
EXPECT_TRUE(PointF(0, 0).IsOrigin());
}
TEST(PointTest, VectorArithmetic) {
Point a(1, 5);
Vector2d v1(3, -3);
Vector2d v2(-8, 1);
static const struct {
Point expected;
Point actual;
} tests[] = {{Point(4, 2), a + v1},
{Point(-2, 8), a - v1},
{a, a - v1 + v1},
{a, a + v1 - v1},
{a, a + Vector2d()},
{Point(12, 1), a + v1 - v2},
{Point(-10, 9), a - v1 + v2}};
for (size_t i = 0; i < 7; ++i)
EXPECT_EQ(tests[i].expected.ToString(), tests[i].actual.ToString());
}
TEST(PointTest, OffsetFromPoint) {
Point a(1, 5);
Point b(-20, 8);
EXPECT_EQ(Vector2d(-20 - 1, 8 - 5).ToString(), (b - a).ToString());
}
TEST(PointTest, ToRoundedPoint) {
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0, 0)));
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0.0001f, 0.0001f)));
EXPECT_EQ(Point(0, 0), ToRoundedPoint(PointF(0.4999f, 0.4999f)));
EXPECT_EQ(Point(1, 1), ToRoundedPoint(PointF(0.5f, 0.5f)));
EXPECT_EQ(Point(1, 1), ToRoundedPoint(PointF(0.9999f, 0.9999f)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10, 10)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10.0001f, 10.0001f)));
EXPECT_EQ(Point(10, 10), ToRoundedPoint(PointF(10.4999f, 10.4999f)));
EXPECT_EQ(Point(11, 11), ToRoundedPoint(PointF(10.5f, 10.5f)));
EXPECT_EQ(Point(11, 11), ToRoundedPoint(PointF(10.9999f, 10.9999f)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10, -10)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10.0001f, -10.0001f)));
EXPECT_EQ(Point(-10, -10), ToRoundedPoint(PointF(-10.4999f, -10.4999f)));
EXPECT_EQ(Point(-11, -11), ToRoundedPoint(PointF(-10.5f, -10.5f)));
EXPECT_EQ(Point(-11, -11), ToRoundedPoint(PointF(-10.9999f, -10.9999f)));
}
TEST(PointTest, Scale) {
EXPECT_EQ(PointF().ToString(), ScalePoint(PointF(), 2).ToString());
EXPECT_EQ(PointF().ToString(), ScalePoint(PointF(), 2, 2).ToString());
EXPECT_EQ(PointF(2, -2).ToString(), ScalePoint(PointF(1, -1), 2).ToString());
EXPECT_EQ(PointF(2, -2).ToString(),
ScalePoint(PointF(1, -1), 2, 2).ToString());
PointF zero;
PointF one(1, -1);
zero.Scale(2);
zero.Scale(3, 1.5);
one.Scale(2);
one.Scale(3, 1.5);
EXPECT_EQ(PointF().ToString(), zero.ToString());
EXPECT_EQ(PointF(6, -3).ToString(), one.ToString());
}
TEST(PointTest, ClampPoint) {
Point a;
a = Point(3, 5);
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(2, 4));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(3, 5));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
a.SetToMax(Point(4, 2));
EXPECT_EQ(Point(4, 5).ToString(), a.ToString());
a.SetToMax(Point(8, 10));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(9, 11));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(8, 10));
EXPECT_EQ(Point(8, 10).ToString(), a.ToString());
a.SetToMin(Point(11, 9));
EXPECT_EQ(Point(8, 9).ToString(), a.ToString());
a.SetToMin(Point(7, 11));
EXPECT_EQ(Point(7, 9).ToString(), a.ToString());
a.SetToMin(Point(3, 5));
EXPECT_EQ(Point(3, 5).ToString(), a.ToString());
}
TEST(PointTest, ClampPointF) {
PointF a;
a = PointF(3.5f, 5.5f);
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(2.5f, 4.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(3.5f, 5.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(4.5f, 2.5f));
EXPECT_EQ(PointF(4.5f, 5.5f).ToString(), a.ToString());
a.SetToMax(PointF(8.5f, 10.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(9.5f, 11.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(8.5f, 10.5f));
EXPECT_EQ(PointF(8.5f, 10.5f).ToString(), a.ToString());
a.SetToMin(PointF(11.5f, 9.5f));
EXPECT_EQ(PointF(8.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(PointF(7.5f, 11.5f));
EXPECT_EQ(PointF(7.5f, 9.5f).ToString(), a.ToString());
a.SetToMin(PointF(3.5f, 5.5f));
EXPECT_EQ(PointF(3.5f, 5.5f).ToString(), a.ToString());
}
TEST(PointTest, Offset) {
Point test(3, 4);
test.Offset(5, -8);
EXPECT_EQ(test, Point(8, -4));
}
TEST(PointTest, VectorMath) {
Point test = Point(3, 4);
test += Vector2d(5, -8);
EXPECT_EQ(test, Point(8, -4));
Point test2 = Point(3, 4);
test2 -= Vector2d(5, -8);
EXPECT_EQ(test2, Point(-2, 12));
}
TEST(PointTest, IntegerOverflow) {
int int_max = std::numeric_limits<int>::max();
int int_min = std::numeric_limits<int>::min();
Point max_point(int_max, int_max);
Point min_point(int_min, int_min);
Point test;
test = Point();
test.Offset(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point();
test.Offset(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point(10, 20);
test.Offset(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test.Offset(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point();
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point();
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point(10, 20);
test += Vector2d(int_max, int_max);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test += Vector2d(int_min, int_min);
EXPECT_EQ(test, min_point);
test = Point();
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, Point(-int_max, -int_max));
test = Point();
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_point);
test = Point(10, 20);
test -= Vector2d(int_min, int_min);
EXPECT_EQ(test, max_point);
test = Point(-10, -20);
test -= Vector2d(int_max, int_max);
EXPECT_EQ(test, min_point);
}
} // namespace gfx
| engine/third_party/accessibility/gfx/geometry/point_unittest.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/point_unittest.cc",
"repo_id": "engine",
"token_count": 3197
} | 455 |
// Copyright (c) 2012 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.
// Defines a simple integer vector class. This class is used to indicate a
// distance in two dimensions between two points. Subtracting two points should
// produce a vector, and adding a vector to a point produces the point at the
// vector's distance from the original point.
#ifndef UI_GFX_GEOMETRY_VECTOR2D_H_
#define UI_GFX_GEOMETRY_VECTOR2D_H_
#include <cstdint>
#include <iosfwd>
#include <string>
#include "gfx/gfx_export.h"
#include "vector2d_f.h"
namespace gfx {
class GFX_EXPORT Vector2d {
public:
constexpr Vector2d() : x_(0), y_(0) {}
constexpr Vector2d(int x, int y) : x_(x), y_(y) {}
constexpr int x() const { return x_; }
void set_x(int x) { x_ = x; }
constexpr int y() const { return y_; }
void set_y(int y) { y_ = y; }
// True if both components of the vector are 0.
bool IsZero() const;
// Add the components of the |other| vector to the current vector.
void Add(const Vector2d& other);
// Subtract the components of the |other| vector from the current vector.
void Subtract(const Vector2d& other);
constexpr bool operator==(const Vector2d& other) const {
return x_ == other.x_ && y_ == other.y_;
}
void operator+=(const Vector2d& other) { Add(other); }
void operator-=(const Vector2d& other) { Subtract(other); }
void SetToMin(const Vector2d& other) {
x_ = x_ <= other.x_ ? x_ : other.x_;
y_ = y_ <= other.y_ ? y_ : other.y_;
}
void SetToMax(const Vector2d& other) {
x_ = x_ >= other.x_ ? x_ : other.x_;
y_ = y_ >= other.y_ ? y_ : other.y_;
}
// Gives the square of the diagonal length of the vector. Since this is
// cheaper to compute than Length(), it is useful when you want to compare
// relative lengths of different vectors without needing the actual lengths.
int64_t LengthSquared() const;
// Gives the diagonal length of the vector.
float Length() const;
std::string ToString() const;
operator Vector2dF() const {
return Vector2dF(static_cast<float>(x()), static_cast<float>(y()));
}
private:
int x_;
int y_;
};
inline constexpr Vector2d operator-(const Vector2d& v) {
return Vector2d(-v.x(), -v.y());
}
inline Vector2d operator+(const Vector2d& lhs, const Vector2d& rhs) {
Vector2d result = lhs;
result.Add(rhs);
return result;
}
inline Vector2d operator-(const Vector2d& lhs, const Vector2d& rhs) {
Vector2d result = lhs;
result.Add(-rhs);
return result;
}
// This is declared here for use in gtest-based unit tests but is defined in
// the //ui/gfx:test_support target. Depend on that to use this in your unit
// test. This should not be used in production code - call ToString() instead.
void PrintTo(const Vector2d& vector, ::std::ostream* os);
} // namespace gfx
#endif // UI_GFX_GEOMETRY_VECTOR2D_H_
| engine/third_party/accessibility/gfx/geometry/vector2d.h/0 | {
"file_path": "engine/third_party/accessibility/gfx/geometry/vector2d.h",
"repo_id": "engine",
"token_count": 1021
} | 456 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "transform.h"
#include "base/string_utils.h"
namespace gfx {
Transform::Transform()
: matrix_{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1},
is_identity_(true) {}
Transform::Transform(float col1row1,
float col2row1,
float col3row1,
float col4row1,
float col1row2,
float col2row2,
float col3row2,
float col4row2,
float col1row3,
float col2row3,
float col3row3,
float col4row3,
float col1row4,
float col2row4,
float col3row4,
float col4row4)
: matrix_{col1row1, col2row1, col3row1, col4row1, col1row2, col2row2,
col3row2, col4row2, col1row3, col2row3, col3row3, col4row3,
col4row4, col2row4, col3row4, col4row4} {
UpdateIdentity();
}
Transform::Transform(float col1row1,
float col2row1,
float col1row2,
float col2row2,
float x_translation,
float y_translation)
: matrix_{col1row1,
col2row1,
x_translation,
0,
col1row2,
col2row2,
y_translation,
0,
0,
0,
1,
0,
0,
0,
0,
1} {
UpdateIdentity();
}
bool Transform::operator==(const Transform& rhs) const {
return matrix_[0] == rhs[0] && matrix_[1] == rhs[1] && matrix_[2] == rhs[2] &&
matrix_[3] == rhs[3] && matrix_[4] == rhs[4] && matrix_[5] == rhs[5] &&
matrix_[6] == rhs[6] && matrix_[7] == rhs[7] && matrix_[8] == rhs[8] &&
matrix_[9] == rhs[9] && matrix_[10] == rhs[10] &&
matrix_[11] == rhs[11] && matrix_[12] == rhs[12] &&
matrix_[13] == rhs[13] && matrix_[14] == rhs[14] &&
matrix_[15] == rhs[15];
}
bool Transform::IsIdentity() const {
return is_identity_;
}
std::string Transform::ToString() const {
return base::StringPrintf(
"[ %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f \n"
" %+0.4f %+0.4f %+0.4f %+0.4f ]\n",
matrix_[0], matrix_[1], matrix_[2], matrix_[3], matrix_[4], matrix_[5],
matrix_[6], matrix_[7], matrix_[8], matrix_[9], matrix_[10], matrix_[11],
matrix_[12], matrix_[13], matrix_[14], matrix_[15]);
}
void Transform::Scale(float x, float y) {
matrix_[0] *= x;
matrix_[5] *= y;
UpdateIdentity();
}
void Transform::TransformRect(RectF* rect) const {
if (IsIdentity())
return;
PointF origin = rect->origin();
PointF top_right = rect->top_right();
PointF bottom_left = rect->bottom_left();
TransformPoint(&origin);
TransformPoint(&top_right);
TransformPoint(&bottom_left);
rect->set_origin(origin);
rect->set_width(top_right.x() - origin.x());
rect->set_height(bottom_left.y() - origin.y());
}
void Transform::TransformPoint(PointF* point) const {
if (IsIdentity())
return;
float x = point->x();
float y = point->y();
point->SetPoint(x * matrix_[0] + y * matrix_[1] + matrix_[2],
x * matrix_[4] + y * matrix_[5] + matrix_[6]);
return;
}
void Transform::UpdateIdentity() {
for (size_t i = 0; i < 16; i++) {
if (i == 0 || i == 5 || i == 10 || i == 15) {
if (matrix_[i] != 1) {
is_identity_ = false;
return;
}
} else {
if (matrix_[i] != 0) {
is_identity_ = false;
return;
}
}
}
is_identity_ = true;
}
} // namespace gfx
| engine/third_party/accessibility/gfx/transform.cc/0 | {
"file_path": "engine/third_party/accessibility/gfx/transform.cc",
"repo_id": "engine",
"token_count": 2135
} | 457 |
# Copyright 2013 The Flutter 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("//flutter/build/dart/dart.gni")
config("config") {
include_dirs = [
"//flutter/third_party",
"//flutter",
]
}
source_set("tonic") {
sources = [
"common/build_config.h",
"common/log.cc",
"common/log.h",
"common/macros.h",
"converter/dart_converter.cc",
"converter/dart_converter.h",
"dart_args.h",
"dart_binding_macros.h",
"dart_class_library.cc",
"dart_class_library.h",
"dart_class_provider.cc",
"dart_class_provider.h",
"dart_library_natives.cc",
"dart_library_natives.h",
"dart_list.cc",
"dart_list.h",
"dart_message_handler.cc",
"dart_message_handler.h",
"dart_microtask_queue.cc",
"dart_microtask_queue.h",
"dart_persistent_value.cc",
"dart_persistent_value.h",
"dart_state.cc",
"dart_state.h",
"dart_weak_persistent_value.cc",
"dart_weak_persistent_value.h",
"dart_wrappable.cc",
"dart_wrappable.h",
"dart_wrapper_info.h",
"file_loader/file_loader.cc",
"file_loader/file_loader.h",
"logging/dart_error.cc",
"logging/dart_error.h",
"logging/dart_invoke.cc",
"logging/dart_invoke.h",
"scopes/dart_api_scope.h",
"scopes/dart_isolate_scope.cc",
"scopes/dart_isolate_scope.h",
"typed_data/dart_byte_data.cc",
"typed_data/dart_byte_data.h",
# Deprecated.
"filesystem/filesystem/eintr_wrapper.h",
"filesystem/filesystem/file.cc",
"filesystem/filesystem/file.h",
"filesystem/filesystem/path.h",
"filesystem/filesystem/portable_unistd.h",
"parsers/packages_map.cc",
"parsers/packages_map.h",
"typed_data/float32_list.h",
"typed_data/float64_list.h",
"typed_data/int32_list.h",
"typed_data/typed_list.cc",
"typed_data/typed_list.h",
"typed_data/uint16_list.h",
"typed_data/uint8_list.h",
]
if (is_win) {
sources += [
"file_loader/file_loader_win.cc",
"filesystem/filesystem/path_win.cc",
]
} else if (is_fuchsia) {
sources += [
"file_loader/file_loader_fuchsia.cc",
"filesystem/filesystem/path_posix.cc",
]
} else {
sources += [
"file_loader/file_loader_posix.cc",
"filesystem/filesystem/path_posix.cc",
]
}
public_deps = [ "$dart_src/runtime:dart_api" ]
public_configs = [ ":config" ]
}
| engine/third_party/tonic/BUILD.gn/0 | {
"file_path": "engine/third_party/tonic/BUILD.gn",
"repo_id": "engine",
"token_count": 1174
} | 458 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tonic/dart_library_natives.h"
#include "tonic/converter/dart_converter.h"
namespace tonic {
DartLibraryNatives::DartLibraryNatives() {}
DartLibraryNatives::~DartLibraryNatives() {}
void DartLibraryNatives::Register(std::initializer_list<Entry> entries) {
for (const Entry& entry : entries) {
symbols_.emplace(entry.native_function, entry.symbol);
entries_.emplace(entry.symbol, entry);
}
}
Dart_NativeFunction DartLibraryNatives::GetNativeFunction(
Dart_Handle name,
int argument_count,
bool* auto_setup_scope) {
std::string name_string = StdStringFromDart(name);
auto it = entries_.find(name_string);
if (it == entries_.end())
return nullptr;
const Entry& entry = it->second;
if (entry.argument_count != argument_count)
return nullptr;
*auto_setup_scope = entry.auto_setup_scope;
return entry.native_function;
}
const uint8_t* DartLibraryNatives::GetSymbol(
Dart_NativeFunction native_function) {
auto it = symbols_.find(native_function);
if (it == symbols_.end())
return nullptr;
return reinterpret_cast<const uint8_t*>(it->second);
}
} // namespace tonic
| engine/third_party/tonic/dart_library_natives.cc/0 | {
"file_path": "engine/third_party/tonic/dart_library_natives.cc",
"repo_id": "engine",
"token_count": 440
} | 459 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef LIB_TONIC_DART_WRAPPER_INFO_H_
#define LIB_TONIC_DART_WRAPPER_INFO_H_
#include <cstddef>
namespace tonic {
class DartWrappable;
typedef void (*DartWrappableAccepter)(DartWrappable*);
struct DartWrapperInfo {
const char* library_name;
const char* interface_name;
DartWrapperInfo(const char* library_name, const char* interface_name)
: library_name(library_name), interface_name(interface_name) {}
private:
DartWrapperInfo(const DartWrapperInfo&) = delete;
DartWrapperInfo& operator=(const DartWrapperInfo&) = delete;
};
} // namespace tonic
#endif // LIB_TONIC_DART_WRAPPER_INFO_H_
| engine/third_party/tonic/dart_wrapper_info.h/0 | {
"file_path": "engine/third_party/tonic/dart_wrapper_info.h",
"repo_id": "engine",
"token_count": 271
} | 460 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
executable("files_unittests") {
testonly = true
sources = [
"directory_unittest.cc",
"file_descriptor_unittest.cc",
"file_unittest.cc",
"files_unittest_main.cc",
"path_unittest.cc",
"scoped_temp_dir_unittest.cc",
]
deps = [ ":../:filesystem" ]
}
| engine/third_party/tonic/filesystem/tests/BUILD.gn/0 | {
"file_path": "engine/third_party/tonic/filesystem/tests/BUILD.gn",
"repo_id": "engine",
"token_count": 172
} | 461 |
# Copyright 2013 The Flutter 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("//flutter/testing/testing.gni")
test_fixtures("tonic_fixtures") {
dart_main = "fixtures/tonic_test.dart"
fixtures = []
}
executable("tonic_unittests") {
testonly = true
public_configs = [ "//flutter:export_dynamic_symbols" ]
sources = [
"../file_loader/file_loader_unittests.cc",
"dart_persistent_handle_unittest.cc",
"dart_state_unittest.cc",
"dart_weak_persistent_handle_unittest.cc",
"ffi_native_unittest.cc",
]
public_deps = [
":tonic_fixtures",
"$dart_src/runtime:dart_api",
"//flutter/lib/snapshot",
"//flutter/runtime:libdart",
"//flutter/runtime:runtime",
"//flutter/testing",
"//flutter/testing:fixture_test",
"//flutter/third_party/googletest:gtest",
]
deps = [ "../:tonic" ]
}
| engine/third_party/tonic/tests/BUILD.gn/0 | {
"file_path": "engine/third_party/tonic/tests/BUILD.gn",
"repo_id": "engine",
"token_count": 382
} | 462 |
/*
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef LIB_TXT_SRC_FONT_FEATURES_H_
#define LIB_TXT_SRC_FONT_FEATURES_H_
#include <map>
#include <string>
#include <vector>
namespace txt {
// Feature tags that can be applied in a text style to control how a font
// selects glyphs.
class FontFeatures {
public:
void SetFeature(std::string tag, int value);
std::string GetFeatureSettings() const;
const std::map<std::string, int>& GetFontFeatures() const;
private:
std::map<std::string, int> feature_map_;
};
// Axis tags and values that can be applied in a text style to control the
// attributes of variable fonts.
class FontVariations {
public:
void SetAxisValue(std::string tag, float value);
const std::map<std::string, float>& GetAxisValues() const;
private:
std::map<std::string, float> axis_map_;
};
} // namespace txt
#endif // LIB_TXT_SRC_FONT_FEATURE_H_
| engine/third_party/txt/src/txt/font_features.h/0 | {
"file_path": "engine/third_party/txt/src/txt/font_features.h",
"repo_id": "engine",
"token_count": 443
} | 463 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef TXT_PLATFORM_MAC_H_
#define TXT_PLATFORM_MAC_H_
#include "txt/asset_font_manager.h"
namespace txt {
// Register additional system font for MacOS and iOS.
void RegisterSystemFonts(const DynamicFontManager& dynamic_font_manager);
} // namespace txt
#endif // TXT_PLATFORM_MAC_H_
| engine/third_party/txt/src/txt/platform_mac.h/0 | {
"file_path": "engine/third_party/txt/src/txt/platform_mac.h",
"repo_id": "engine",
"token_count": 151
} | 464 |
//---------------------------------------------------------------------------------------------
// Copyright (c) 2022 Google LLC
// Licensed under the MIT License. See License.txt in the project root for license information.
//--------------------------------------------------------------------------------------------*/
library web_locale_keymap;
export 'web_locale_keymap/key_mappings.g.dart';
export 'web_locale_keymap/locale_keymap.dart';
| engine/third_party/web_locale_keymap/lib/web_locale_keymap.dart/0 | {
"file_path": "engine/third_party/web_locale_keymap/lib/web_locale_keymap.dart",
"repo_id": "engine",
"token_count": 95
} | 465 |
# API consistency check tool
Verifies that enums in each of the platform-specific embedders, and the embedder
API remain consistent with their API in dart:ui.
### Running the tool
This tool is run as part of `testing/run_tests.sh`.
To run the tool, invoke with the path of the Flutter engine repo as the first
argument.
```
../../../out/host_debug_unopt/dart-sdk/bin/dart \
--disable-dart-dev \
test/apicheck_test.dart \
"$(dirname $(dirname $PWD))"
```
| engine/tools/api_check/README.md/0 | {
"file_path": "engine/tools/api_check/README.md",
"repo_id": "engine",
"token_count": 204
} | 466 |
#!/bin/bash
set -e
set -x
if [[ -z $ENGINE_PATH ]]
then
echo "Please set ENGINE_PATH environment variable."
exit 1
fi
# Go to the engine git repo to get the date of the latest commit.
cd $ENGINE_PATH/src/flutter
ENGINE_COMMIT=`git rev-parse HEAD`
echo "Using engine commit: $ENGINE_COMMIT"
if [[ -z $FLUTTER_CLONE_REPO_PATH ]]
then
echo "Please set FLUTTER_CLONE_REPO_PATH environment variable."
exit 1
else
cd $FLUTTER_CLONE_REPO_PATH
fi
if [[ $GIT_BRANCH =~ ^flutter-.*-candidate.*$ ]]
then
# Coming from presubmit and assuming the correct branch has been already checked out.
COMMIT_NO=`git rev-parse HEAD`
else
# Try to get release branch from the checkout.
RELEASE_BRANCH=`git branch -a --contains $ENGINE_COMMIT | grep 'flutter-.*-candidate.*' || true`
if [[ -z $RELEASE_BRANCH ]]
then
# If this is not a release branch commit get latest commit's time for the engine repo.
# Use date based on local time otherwise timezones might get mixed.
LATEST_COMMIT_TIME_ENGINE=`git log -1 --date=local --format="%cd"`
echo "Latest commit time on engine found as $LATEST_COMMIT_TIME_ENGINE"
# Get the time of the youngest commit older than engine commit.
# Git log uses commit date not the author date.
# Before makes the comparison considering the timezone as well.
COMMIT_NO=`git log --before="$LATEST_COMMIT_TIME_ENGINE" -n 1 | grep commit | cut -d ' ' -f2`
else
COMMIT_NO=`git rev-parse $RELEASE_BRANCH`
git checkout $RELEASE_BRANCH
fi
fi
echo "Using the flutter/flutter commit $COMMIT_NO";
git reset --hard $COMMIT_NO
# Write the commit number to a file. This file will be read by the LUCI recipe.
echo "$COMMIT_NO" >> flutter_ref.txt
# Print out the flutter version for troubleshooting
$FLUTTER_CLONE_REPO_PATH/bin/flutter --version -v
| engine/tools/configure_framework_commit.sh/0 | {
"file_path": "engine/tools/configure_framework_commit.sh",
"repo_id": "engine",
"token_count": 634
} | 467 |
# dir_contents_diff
This tool will compare the contents of a directory to a file that lists the
contents of the directory, printing out a patch to apply if they differ.
The exit code is 0 if there is no difference.
## Usage
```sh
dart run ./bin/dir_contents_diff.dart <golden file path> <dir path>
```
| engine/tools/dir_contents_diff/README.md/0 | {
"file_path": "engine/tools/dir_contents_diff/README.md",
"repo_id": "engine",
"token_count": 93
} | 468 |
// Copyright 2013 The Flutter 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 'dart:io' as io show Directory;
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:path/path.dart' as p;
import 'environment.dart';
import 'logger.dart';
/// A function that returns true or false when given a [BuilderConfig] and its
/// name.
typedef ConfigFilter = bool Function(String name, BuilderConfig config);
/// A function that returns true or false when given a [BuilderConfig] name
/// and a [Build].
typedef BuildFilter = bool Function(String configName, Build build);
/// Returns a filtered copy of [input] filtering out configs where test
/// returns false.
Map<String, BuilderConfig> filterBuilderConfigs(
Map<String, BuilderConfig> input, ConfigFilter test) {
return <String, BuilderConfig>{
for (final MapEntry<String, BuilderConfig> entry in input.entries)
if (test(entry.key, entry.value)) entry.key: entry.value,
};
}
/// Returns a copy of [input] filtering out configs that are not runnable
/// on the current platform.
Map<String, BuilderConfig> runnableBuilderConfigs(
Environment env, Map<String, BuilderConfig> input) {
return filterBuilderConfigs(input, (String name, BuilderConfig config) {
return config.canRunOn(env.platform);
});
}
/// Returns a List of [Build] that match test.
List<Build> filterBuilds(Map<String, BuilderConfig> input, BuildFilter test) {
return <Build>[
for (final MapEntry<String, BuilderConfig> entry in input.entries)
for (final Build build in entry.value.builds)
if (test(entry.key, build)) build,
];
}
/// Returns a list of runnable builds.
List<Build> runnableBuilds(Environment env, Map<String, BuilderConfig> input) {
return filterBuilds(input, (String configName, Build build) {
return build.canRunOn(env.platform);
});
}
/// Validates the list of builds.
/// Calls assert.
void debugCheckBuilds(List<Build> builds) {
final Set<String> names = <String>{};
for (final Build build in builds) {
assert(!names.contains(build.name),
'More than one build has the name ${build.name}');
names.add(build.name);
}
}
/// Build the build target in the environment.
Future<int> runBuild(
Environment environment,
Build build, {
List<String> extraGnArgs = const <String>[],
}) async {
// If RBE config files aren't in the tree, then disable RBE.
final String rbeConfigPath = p.join(
environment.engine.srcDir.path,
'flutter',
'build',
'rbe',
);
final List<String> gnArgs = <String>[
...extraGnArgs,
if (!io.Directory(rbeConfigPath).existsSync()) '--no-rbe',
];
final BuildRunner buildRunner = BuildRunner(
platform: environment.platform,
processRunner: environment.processRunner,
abi: environment.abi,
engineSrcDir: environment.engine.srcDir,
build: build,
extraGnArgs: gnArgs,
runTests: false,
);
Spinner? spinner;
void handler(RunnerEvent event) {
switch (event) {
case RunnerStart():
environment.logger.status('$event ', newline: false);
spinner = environment.logger.startSpinner();
case RunnerProgress(done: true):
spinner?.finish();
spinner = null;
environment.logger.clearLine();
environment.logger.status(event);
case RunnerProgress(done: false):
{
spinner?.finish();
spinner = null;
final String percent = '${event.percent.toStringAsFixed(1)}%';
final String fraction = '(${event.completed}/${event.total})';
final String prefix = '[${event.name}] $percent $fraction ';
final String what = event.what;
environment.logger.clearLine();
environment.logger.status('$prefix$what', newline: false, fit: true);
}
default:
spinner?.finish();
spinner = null;
environment.logger.status(event);
}
}
final bool buildResult = await buildRunner.run(handler);
return buildResult ? 0 : 1;
}
| engine/tools/engine_tool/lib/src/build_utils.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/build_utils.dart",
"repo_id": "engine",
"token_count": 1429
} | 469 |
// Copyright 2013 The Flutter 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 'dart:convert';
import 'package:process_runner/process_runner.dart';
import 'environment.dart';
import 'json_utils.dart';
const String _targetPlatformKey = 'targetPlatform';
const String _nameKey = 'name';
const String _idKey = 'id';
/// Target to run a flutter application on.
class RunTarget {
/// Construct a RunTarget from a JSON map.
factory RunTarget.fromJson(Map<String, Object> map) {
final List<String> errors = <String>[];
final String name = stringOfJson(map, _nameKey, errors)!;
final String id = stringOfJson(map, _idKey, errors)!;
final String targetPlatform =
stringOfJson(map, _targetPlatformKey, errors)!;
if (errors.isNotEmpty) {
throw FormatException('Failed to parse RunTarget: ${errors.join('\n')}');
}
return RunTarget._(name, id, targetPlatform);
}
RunTarget._(this.name, this.id, this.targetPlatform);
/// Name of target device.
final String name;
/// Id of target device.
final String id;
/// Target platform of device.
final String targetPlatform;
/// BuildConfig name for compilation mode.
String buildConfigFor(String mode) {
switch (targetPlatform) {
case 'android-arm64':
return 'android_${mode}_arm64';
case 'darwin':
return 'host_$mode';
case 'web-javascript':
return 'chrome_$mode';
default:
throw UnimplementedError('No mapping for $targetPlatform');
}
}
}
/// Parse the raw output of `flutter devices --machine`.
List<RunTarget> parseDevices(Environment env, String flutterDevicesMachine) {
late final List<dynamic> decoded;
try {
decoded = jsonDecode(flutterDevicesMachine) as List<dynamic>;
} on FormatException catch (e) {
env.logger.error(
'Failed to parse flutter devices output: $e\n\n$flutterDevicesMachine\n\n');
return <RunTarget>[];
}
final List<RunTarget> r = <RunTarget>[];
for (final dynamic device in decoded) {
if (device is! Map<String, Object?>) {
return <RunTarget>[];
}
if (!device.containsKey(_nameKey) || !device.containsKey(_idKey)) {
env.logger.error('device is missing required fields:\n$device\n');
return <RunTarget>[];
}
if (!device.containsKey(_targetPlatformKey)) {
env.logger.warning('Skipping ${device[_nameKey]}: '
'Could not find $_targetPlatformKey in device description.');
continue;
}
late final RunTarget target;
try {
target = RunTarget.fromJson(device.cast<String, Object>());
} on FormatException catch (e) {
env.logger.error(e);
return <RunTarget>[];
}
r.add(target);
}
return r;
}
/// Return the default device to be used.
RunTarget? defaultDevice(Environment env, List<RunTarget> targets) {
if (targets.isEmpty) {
return null;
}
return targets.first;
}
/// Select a run target.
RunTarget? selectRunTarget(Environment env, String flutterDevicesMachine,
[String? idPrefix]) {
final List<RunTarget> targets = parseDevices(env, flutterDevicesMachine);
if (idPrefix != null && idPrefix.isNotEmpty) {
for (final RunTarget target in targets) {
if (target.id.startsWith(idPrefix)) {
return target;
}
}
}
return defaultDevice(env, targets);
}
/// Detects available targets and then selects one.
Future<RunTarget?> detectAndSelectRunTarget(Environment env,
[String? idPrefix]) async {
final ProcessRunnerResult result = await env.processRunner
.runProcess(<String>['flutter', 'devices', '--machine']);
if (result.exitCode != 0) {
env.logger.error('flutter devices --machine failed:\n'
'EXIT_CODE:${result.exitCode}\n'
'STDOUT:\n${result.stdout}'
'STDERR:\n${result.stderr}');
return null;
}
return selectRunTarget(env, result.stdout, idPrefix);
}
| engine/tools/engine_tool/lib/src/run_utils.dart/0 | {
"file_path": "engine/tools/engine_tool/lib/src/run_utils.dart",
"repo_id": "engine",
"token_count": 1416
} | 470 |
# Copyright 2013 The Flutter 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("//flutter/build/zip_bundle.gni")
executable("_font-subset") {
output_name = "font-subset"
sources = [
"hb_wrappers.h",
"main.cc",
]
deps = [ "//flutter/third_party/harfbuzz:harfbuzz_subset" ]
if (is_mac) {
frameworks = [
"Foundation.framework",
"CoreGraphics.framework",
"CoreText.framework",
]
}
metadata = {
font_subset_without_entitlement = [ "font-subset" ]
}
}
generated_file("font_entitlement_config") {
outputs = [ "$target_gen_dir/font_subset_without_entitlements.txt" ]
data_keys = [ "font_subset_without_entitlement" ]
deps = [ ":_font-subset" ]
}
zip_bundle("font_subset") {
if (is_mac) {
# Mac artifacts sometimes use mac and sometimes darwin. Standardizing the
# names will require changes in the list of artifacts the tool is downloading.
output = "darwin-${target_cpu}/font-subset.zip"
} else {
output = "${full_target_platform_name}/font-subset.zip"
}
font_subset_bin = "font-subset"
if (is_win) {
font_subset_bin = "${font_subset_bin}.exe"
}
files = [
{
source = "$root_build_dir/$font_subset_bin"
destination = font_subset_bin
},
{
source = "$root_gen_dir/const_finder.dart.snapshot"
destination = "const_finder.dart.snapshot"
},
]
deps = [
":_font-subset",
"//flutter/tools/const_finder",
]
if (is_mac) {
deps += [ ":font_entitlement_config" ]
files += [
{
source = "$target_gen_dir/font_subset_without_entitlements.txt"
destination = "without_entitlements.txt"
},
]
}
}
| engine/tools/font_subset/BUILD.gn/0 | {
"file_path": "engine/tools/font_subset/BUILD.gn",
"repo_id": "engine",
"token_count": 727
} | 471 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
declare_args() {
# The default clang toolchain provided by the prebuilt. This variable is
# additionally consumed by the Go toolchain.
clang_base = rebase_path("//buildtools/${host_os}-${host_cpu}/clang/lib")
}
if (current_cpu == "arm64") {
clang_cpu = "aarch64"
} else if (current_cpu == "x64") {
clang_cpu = "x86_64"
} else {
assert(false, "CPU not supported")
}
if (is_fuchsia) {
clang_target = "${clang_cpu}-fuchsia"
} else if (is_linux) {
clang_target = "${clang_cpu}-linux-gnu"
} else if (is_mac) {
clang_target = "${clang_cpu}-apple-darwin"
} else {
assert(false, "OS not supported")
}
clang_manifest = rebase_path("$clang_base/runtime.json")
clang_manifest_json = exec_script("//flutter/tools/fuchsia/parse_manifest.py",
[
"--input=${clang_manifest}",
"--clang-cpu=${clang_cpu}",
],
"json")
| engine/tools/fuchsia/clang.gni/0 | {
"file_path": "engine/tools/fuchsia/clang.gni",
"repo_id": "engine",
"token_count": 546
} | 472 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# NOTE: Generally, the build rules in //flutter/tools/fuchsia/dart/,
# //flutter/tools/fuchsia/dart/kernel/, and similar SUBDIRECTORIES of
# //flutter/tools/fuchsia/ (such as //flutter/tools/fuchsia/flutter/)
# mirror the directory paths and much of the build rule content of fuchsia.git
# //build/...
#
# Most of the fuchsia-derived build rules were implemented after some similar
# build rules already existed in the directory //flutter/tools/fuchsia/
# and several existing build targets use these (legacy) build rules.
# Though some rules and targets in //flutter/tools/fuchsia/ have similar names
# to the fuchsia.git-derived rules, the rule structures and behavior can be
# different. Therefore both are maintained for now.
#
# This file--dart_kernel.gni--and its primary template--dart_kernel()--match
# pre-existing (legacy) template and filename in
# //flutter/tools/fuchsia/dart_kernel.gni.
#
# The templates appear to have different behavior, so both will be maintained
# until we can determine a better way to reconcile them.
import("//flutter/tools/fuchsia/dart/config.gni")
import("//flutter/tools/fuchsia/dart/dart_library.gni")
import("//flutter/tools/fuchsia/dart/toolchain.gni")
_gen_kernel_label =
"//flutter/tools/fuchsia/dart/kernel:gen_kernel($host_toolchain)"
_gen_kernel_path =
get_label_info(_gen_kernel_label, "root_out_dir") + "/dart-tools/gen_kernel"
flutter_platform_name = "flutter_runner"
dart_platform_name = "dart_runner"
# Converts the kernel manifest file from fini format to JSON format and
# registers the metadata for the fuchsia_package to pick up.
#
# Parameters
#
# manifest (required)
# Path to the kernel manifest
# Type: Path
template("_convert_kernel_manifest") {
assert(defined(invoker.manifest), "dart_kernel() requires a manifest")
action(target_name) {
forward_variables_from(invoker,
[
"deps",
"testonly",
"visibility",
])
_converted_file_name =
"${target_gen_dir}/${target_name}_kernel_manifest.json"
script = "//flutter/tools/fuchsia/dart/kernel/convert_manifest_to_json.py"
args = [
"--path_prefix",
rebase_path(root_out_dir) + "/",
"--input",
rebase_path(invoker.manifest, root_build_dir),
"--output",
rebase_path(_converted_file_name, root_build_dir),
]
sources = [ invoker.manifest ]
outputs = [ _converted_file_name ]
metadata = {
distribution_entries = [
{
file = rebase_path(_converted_file_name, root_build_dir)
label = get_label_info(target_name, "label_with_toolchain")
},
]
}
}
}
# Generates dill files for a Dart application.
#
# It is not likely that this target will be used directly. Instead, developers
# should use the dart_tool or dart/flutter_component targets which create a
# kernel for you.
#
# Parameters
#
# platform_name (required)
# The name of the platform, either "flutter_runner" or "dart_runner".
#
# packages_path (required)
# Path to the package_config.json file.
#
# main_dart (required, mutually exclusive)
# Path to Dart source file containing main(). Mutually exclusive with
# main_dart_file. This is relative to source_dir, should exist in the
# main_package, and uses a package: URI.
#
# main_package (required, mutually exclusive)
# The name of the package which contains main. Mutually exclusive with
# main_dart_file.
#
# main_dart_file (required, mutually exclusive)
# Path to Dart source file containing main(). Mutually exclusive with
# main_dart. This doesn't need to necessarily exist in main_package and uses
# a fuchsia-source: URI.
#
# product (required)
# Whether this should be built with the product runner.
#
# is_aot required)
# Whether this kernel is an aot build.
#
# generate_manifest (optional)
# Whether the compiler should generate a kernel manifest containing the list
# of partial dill files in JIT builds. This flag is ignored in aot builds
# Default: false
#
# kernel_path (optional)
# The path to the kernel output. Defaults to target_gen_dir/${target_name}.dil
#
# kernel_target_name (optional)
# The name of the kernel target. This parameter is required if you are
# depending on the kernel_path for an input. This allows you to establish a
# dependency chain on the generated file.
#
# args (optional)
# A list of additional arguments to the compiler.dart program in this
# directory that generates the kernel files.
#
# link_platform (optional)
# Whether the kernel compiler should link the current platform.dill into
# the build. If false, the --no-link-platform flag will be passed to the
# compiler. Defaults to false.
template("dart_kernel") {
assert(defined(invoker.platform_name), "dart_kernel() requires platform_name")
assert(defined(invoker.packages_path),
"dart_kernel() requires the path to the package config")
assert(
(defined(invoker.main_dart) && defined(invoker.main_package)) !=
defined(invoker.main_dart_file),
"dart_kernel() requires either (main_dart and main_package) or main_dart_file")
assert(defined(invoker.product), "dart_kernel() requires product")
assert(defined(invoker.is_aot), "dart_kernel() requires is_aot")
if (defined(invoker.kernel_target_name)) {
_kernel_target_name = invoker.kernel_target_name
} else {
_kernel_target_name = "${target_name}_kernel"
}
_group_deps = [ ":$_kernel_target_name" ]
_kernel_deps = []
if (defined(invoker.deps)) {
_kernel_deps += invoker.deps
}
# TODO(richkadel): The manifest (if not using AOT) is used by
# flutter_dart_component, to populate the file it calls
# `_convert_kernel_manifest_file`.
_generate_manifest = false
if (invoker.is_aot) {
not_needed(invoker, [ "generate_manifest" ])
} else {
if (defined(invoker.generate_manifest)) {
_generate_manifest = invoker.generate_manifest
}
}
if (_generate_manifest) {
_kernel_manifest = "$target_gen_dir/${target_name}.dilpmanifest"
_convert_target_name = "${target_name}_convert_kernel_manifest"
_convert_kernel_manifest(_convert_target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
manifest = _kernel_manifest
# must depend on the kernel target so we have the kernel manifest
deps = [ ":$_kernel_target_name" ]
}
_group_deps += [ ":$_convert_target_name" ]
}
action(_kernel_target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
if (defined(invoker.kernel_path)) {
_kernel_path = invoker.kernel_path
} else {
_kernel_path =
"$target_gen_dir/__untraced_dart_kernel__/${target_name}.dil"
}
depfile = "${_kernel_path}.d"
_kernel_deps += [ _gen_kernel_label ]
if (invoker.platform_name == flutter_platform_name) {
_kernel_deps += [
"//flutter/shell/platform/fuchsia/flutter/kernel:kernel_platform_files",
]
_platform_path = "$root_out_dir/flutter_runner_patched_sdk"
} else if (invoker.platform_name == dart_platform_name) {
_kernel_deps += [ "//flutter/shell/platform/fuchsia/dart_runner/kernel:kernel_platform_files" ]
_platform_path = "$root_out_dir/dart_runner_patched_sdk"
} else {
assert(false,
"platform_name must be either dart_runner or flutter_runner")
}
_platform_strong_dill = "${_platform_path}/platform_strong.dill"
inputs = [
_gen_kernel_path,
_platform_strong_dill,
invoker.packages_path,
]
outputs = [ _kernel_path ]
if (_generate_manifest) {
outputs += [
# Explicit output when using --manifest.
_kernel_manifest,
# Implicit output when using --manifest; see createManifest in compiler.dart.
_kernel_manifest + ".dilplist",
_kernel_manifest + ".frameworkversion",
]
}
_multi_root_scheme = "fuchsia-source"
# Rebase against // instead of root_build_dir since the package_config is
# relative to the sources.
_rebased_packages_path = rebase_path(invoker.packages_path, "//")
# gen_kernel writes absolute paths to depfiles, convert them to relative.
# See more information in https://fxbug.dev/75451.
script = "//flutter/tools/fuchsia/depfile_path_to_relative.py"
args = [
"--depfile=" + rebase_path(depfile, root_build_dir),
"--",
rebase_path(_gen_kernel_path, root_out_dir),
]
if (defined(invoker.args)) {
args += invoker.args
}
args += [
"--verbosity=warning",
"--target",
invoker.platform_name,
"--platform",
rebase_path(_platform_strong_dill, root_build_dir),
"--filesystem-scheme",
_multi_root_scheme,
"--filesystem-root",
rebase_path("//"),
"--packages",
"$_multi_root_scheme:///$_rebased_packages_path",
# Repeating "--depfile" because the previous one is for
# `depfile_path_to_relative.py`, and this one is for `_gen_kernel_path`.
"--depfile",
rebase_path(depfile, root_build_dir),
"--output",
rebase_path(_kernel_path, root_build_dir),
"--sound-null-safety",
]
# TODO(richkadel): It should be possible to remove all of the build rules
# related to `generate_manifest`. Without the following two flags, the
# `gen_kernel` step will produce one large `.dil` file, instead of multiple
# `.dilp` files with a `.dilplist`. But the Fuchsia flutter runner
# _currently_ only looks for a `.dilplist`. If the runner is changed to
# support loading a single `.dil` for the Dart Fuchsia component code, then
# consider removing all code supporting `generate_manifest` (and remove
# `convert_manifest_to_json.py`).
if (_generate_manifest) {
args += [
"--split-output-by-packages",
"--manifest",
rebase_path(_kernel_manifest, root_build_dir),
]
}
if (flutter_runtime_mode == "debug") {
args += [ "--embed-sources" ]
} else {
args += [ "--no-embed-sources" ]
}
if (invoker.is_aot) {
args += [
"--aot",
"--tfa",
]
} else if (!defined(invoker.link_platform) || !invoker.link_platform) {
args += [ "--no-link-platform" ]
}
if (invoker.product) {
# Setting this flag in a non-product release build for AOT (a "profile"
# build) causes the vm service isolate code to be tree-shaken from an app.
# See the pragma on the entrypoint here:
#
# This define excludes debugging and profiling code from Flutter.
args += [ "-Ddart.vm.product=true" ]
} else {
if (flutter_runtime_mode == "profile") {
# The following define excludes debugging code from Flutter.
args += [ "-Ddart.vm.profile=true" ]
}
}
if (defined(invoker.main_dart)) {
args += [ "package:${invoker.main_package}/${invoker.main_dart}" ]
} else {
rebased_main_dart = rebase_path(invoker.main_dart_file, "//")
args += [ "$_multi_root_scheme:///$rebased_main_dart" ]
}
deps = _kernel_deps
}
group(target_name) {
forward_variables_from(invoker,
[
"testonly",
"visibility",
])
public_deps = _group_deps
}
}
| engine/tools/fuchsia/dart/kernel/dart_kernel.gni/0 | {
"file_path": "engine/tools/fuchsia/dart/kernel/dart_kernel.gni",
"repo_id": "engine",
"token_count": 4775
} | 473 |
# Copyright 2013 The Flutter 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("//flutter/common/config.gni")
# Non-product JIT is "debug". It launches the vm service.
# Non-product AOT is "profile". It also launches the vm service, but lacks tools that rely on JIT.
# Product JIT is "release". It doesn't launch the vm service.
# Product AOT is "release". It doesn't launch the vm service.
# Builds the component in a non-product JIT build. This will
# launch the vm service in the runner.
flutter_debug_build_cfg = {
runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_jit_runner"
platform_name = "flutter_runner"
is_aot = false
is_product = false
enable_asserts = true
}
# Builds the component in a non-product AOT build. This will
# launch the vm service in the runner.
# This configuration is not compatible with a --release build since the
# profile aot runner is built without asserts.
flutter_aot_debug_build_cfg = {
runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_aot_runner"
platform_name = "flutter_runner"
is_aot = true
is_product = false
enable_asserts = true
}
# Builds the component in a non-product AOT build. This will
# launch the vm service in the runner.
flutter_profile_build_cfg = {
runner_dep = "//flutter/shell/platform/fuchsia/flutter:flutter_aot_runner"
platform_name = "flutter_runner"
is_aot = true
is_product = false
enable_asserts = false
}
# Builds the component in a product JIT build. This will
# not launch the vm service in the runner.
flutter_jit_release_build_cfg = {
runner_dep =
"//flutter/shell/platform/fuchsia/flutter:flutter_jit_product_runner"
platform_name = "flutter_runner"
is_aot = false
is_product = true
enable_asserts = false
}
# Builds the component in a product AOT build. This will
# not launch the vm service in the runner.
flutter_release_build_cfg = {
runner_dep =
"//flutter/shell/platform/fuchsia/flutter:flutter_aot_product_runner"
platform_name = "flutter_runner"
is_aot = true
is_product = true
enable_asserts = false
}
| engine/tools/fuchsia/flutter/flutter_build_config.gni/0 | {
"file_path": "engine/tools/fuchsia/flutter/flutter_build_config.gni",
"repo_id": "engine",
"token_count": 707
} | 474 |
# Copyright 2013 The Flutter 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("//flutter/tools/fuchsia/toolchain/default_tools.gni")
declare_args() {
toolchain_variant = {
}
}
# Define a basic GN toolchain() instance that only has the "stamp" and "copy"
# tools. Use this for toolchains that will only have action() targets.
#
# Parameters:
# expected_label: Optional
# If provided, this template will assert that the full toolchain label
# matches this value. This is useful when the definition should match
# a global variable (e.g. go_toolchain or dart_toolchain).
# Type: GN label
#
# toolchain_args: Optional
# A scope of extra toolchain_args keys for this toolchain instance.
#
# NOTE: This also ensures this defines the global `toolchain_variant.base`
# variable, allowing BUILDCONFIG.gn to detect that this is not the default
# toolchain (see the definition of in_default_toolchain in that file for
# more details).
template("basic_toolchain") {
# The line below is required, otherwise 'gn gen' will complain with an error
# (i.e. 'You set the variable "invoker" here and it was unused before it went
# out of scope') if the template is called without any arguments.
not_needed([ "invoker" ])
toolchain(target_name) {
tool("stamp") {
command = stamp_command
description = stamp_description
}
tool("copy") {
command = copy_command
description = copy_description
}
toolchain_args = {
if (defined(invoker.toolchain_args)) {
forward_variables_from(invoker.toolchain_args, "*")
}
toolchain_variant = {
base = get_label_info(":$target_name", "label_no_toolchain")
if (defined(invoker.expected_label)) {
assert(
base == invoker.expected_label,
"Invalid toolchain label $base, expected ${invoker.expected_label}")
}
}
}
}
}
| engine/tools/fuchsia/toolchain/basic_toolchain.gni/0 | {
"file_path": "engine/tools/fuchsia/toolchain/basic_toolchain.gni",
"repo_id": "engine",
"token_count": 693
} | 475 |
// Copyright 2014 The Flutter 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 'package:meta/meta.dart' show immutable;
/// A subtree of a JSON object as well as its path.
@immutable
class JsonContext<T> {
/// Create a [JsonContext] that represents a subtree.
const JsonContext(this.current, this.path);
/// The content of the subtree.
final T current;
/// The path from the root.
final List<String> path;
/// Create a [JsonContext] that represents the root of a tree.
static JsonContext<Map<String, dynamic>> root(Map<String, dynamic> root) {
return JsonContext<Map<String, dynamic>>(root, const <String>[]);
}
}
/// A JSON object.
typedef JsonObject = Map<String, dynamic>;
/// A JSON array.
typedef JsonArray = List<dynamic>;
String _jsonTypeErrorMessage(List<String> currentPath, String nextKey, Type expectedType, Type actualType) {
return 'Unexpected value at path ${currentPath.join('.')}.$nextKey: '
'Expects $expectedType but got $actualType.';
}
/// Returns a JSON object's specified key.
///
/// If the result is not of type `T`, throws an `ArgumentError`.
JsonContext<T> jsonGetKey<T>(JsonContext<JsonObject> context, String key) {
final dynamic result = context.current[key];
if (result is! T) {
throw ArgumentError(_jsonTypeErrorMessage(context.path, key, T, result.runtimeType));
}
return JsonContext<T>(result, <String>[...context.path, key]);
}
/// Returns a JSON array's specified index.
///
/// If the subtree is not of type `T`, throws an `ArgumentError`.
JsonContext<T> jsonGetIndex<T>(JsonContext<JsonArray> context, int index) {
final dynamic result = context.current[index];
if (result is! T) {
throw ArgumentError(_jsonTypeErrorMessage(context.path, '$index', T, result.runtimeType));
}
return JsonContext<T>(result, <String>[...context.path, '$index']);
}
List<dynamic> _jsonPathSplit(String path) {
return path.split('.').map((String key) {
final int? index = int.tryParse(key);
if (index != null) {
return index;
} else {
return key;
}
}).toList();
}
/// Returns the value at `path` of a JSON tree.
///
/// The path is split using `.`. Integral elements are considered as array
/// indexes, while others are considered as map indexes.
///
/// If the final result is not of type `T`, throws an `ArgumentError`.
JsonContext<T> jsonGetPath<T>(JsonContext<dynamic> context, String path) {
JsonContext<dynamic> current = context;
void jsonGetKeyOrIndex<M>(dynamic key, int depth) {
assert(key is String || key is int, 'Key at $depth is a ${key.runtimeType}.');
if (key is String) {
current = jsonGetKey<M>(current as JsonContext<JsonObject>, key);
} else if (key is int) {
current = jsonGetIndex<M>(current as JsonContext<JsonArray>, key);
} else {
assert(false);
}
}
void jsonGetKeyOrIndexForNext(dynamic key, dynamic nextKey, int depth) {
assert(nextKey is String || nextKey is int, 'Key at ${depth + 1} is a ${key.runtimeType}.');
if (nextKey is String) {
jsonGetKeyOrIndex<JsonObject>(key, depth);
} else if (nextKey is int) {
jsonGetKeyOrIndex<JsonArray>(key, depth);
} else {
assert(false);
}
}
final List<dynamic> pathSegments = _jsonPathSplit(path);
for (int depth = 0; depth < pathSegments.length; depth += 1) {
if (depth != pathSegments.length - 1) {
jsonGetKeyOrIndexForNext(pathSegments[depth], pathSegments[depth + 1], depth);
} else {
jsonGetKeyOrIndex<T>(pathSegments[depth], depth);
}
}
return current as JsonContext<T>;
}
| engine/tools/gen_web_locale_keymap/lib/json_get.dart/0 | {
"file_path": "engine/tools/gen_web_locale_keymap/lib/json_get.dart",
"repo_id": "engine",
"token_count": 1251
} | 476 |
#!/usr/bin/env python3
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
'''
Sets up githooks.
'''
import os
import subprocess
import sys
SRC_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)
FLUTTER_DIR = os.path.join(SRC_ROOT, 'flutter')
def IsWindows():
os_id = sys.platform
return os_id.startswith('win32') or os_id.startswith('cygwin')
def Main(argv):
git = 'git'
githooks = os.path.join(FLUTTER_DIR, 'tools', 'githooks')
if IsWindows():
git = 'git.bat'
result = subprocess.run([
git,
'config',
'core.hooksPath',
githooks,
], cwd=FLUTTER_DIR)
return result.returncode
if __name__ == '__main__':
sys.exit(Main(sys.argv))
| engine/tools/githooks/setup.py/0 | {
"file_path": "engine/tools/githooks/setup.py",
"repo_id": "engine",
"token_count": 347
} | 477 |
// Copyright 2013 The Flutter 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 'dart:io' as io;
import 'package:header_guard_check/header_guard_check.dart';
Future<int> main(List<String> arguments) async {
final int result = await HeaderGuardCheck.fromCommandLine(arguments).run();
if (result != 0) {
io.exit(result);
}
return result;
}
| engine/tools/header_guard_check/bin/main.dart/0 | {
"file_path": "engine/tools/header_guard_check/bin/main.dart",
"repo_id": "engine",
"token_count": 139
} | 478 |
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
| engine/tools/licenses/data/gpl-3.0/0 | {
"file_path": "engine/tools/licenses/data/gpl-3.0",
"repo_id": "engine",
"token_count": 8076
} | 479 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// See README in this directory for information on how this code is organized.
import 'dart:core' hide RegExp;
import 'dart:io' as system;
import 'dart:math' as math;
import 'package:args/args.dart';
import 'package:collection/collection.dart' show IterableExtension;
import 'package:crypto/crypto.dart' as crypto;
import 'package:path/path.dart' as path;
import 'filesystem.dart' as fs;
import 'licenses.dart';
import 'paths.dart';
import 'patterns.dart';
import 'regexp_debug.dart';
abstract class _RepositoryEntry implements Comparable<_RepositoryEntry> {
_RepositoryEntry(this.parent, this.io);
final _RepositoryDirectory? parent;
final fs.IoNode io;
String get name => io.name;
@override
int compareTo(_RepositoryEntry other) => toString().compareTo(other.toString());
@override
String toString() => io.fullName;
}
abstract class _RepositoryFile extends _RepositoryEntry {
_RepositoryFile(_RepositoryDirectory super.parent, fs.File super.io);
fs.File get ioFile => super.io as fs.File;
}
abstract class _RepositoryLicensedFile extends _RepositoryFile {
_RepositoryLicensedFile(super.parent, super.io);
// Returns the License that is found inside this file.
//
// Used when one file says it is covered by the license of another file.
License extractInternalLicense() {
throw 'tried to extract a license from $this but it does not contain text';
}
// Creates the mapping from the file to its licenses.
//
// Subclasses implement things like applying licenses found within the file
// itself, applying licenses that point to other files, etc.
//
// The assignments are later grouped when generating the output, see
// groupLicenses in licenses.dart.
Iterable<Assignment> assignLicenses() {
final List<License> licenses = parent!.nearestLicensesFor(name);
if (licenses.isEmpty) {
throw 'file has no detectable license and no in-scope default license file';
}
return licenses.map((License license) => license.assignLicenses(io.fullName, parent!));
}
}
class _RepositorySourceFile extends _RepositoryLicensedFile {
_RepositorySourceFile(super.parent, fs.TextFile super.io) : _contents = _readFile(io);
fs.TextFile get ioTextFile => super.io as fs.TextFile;
final String _contents;
static String _readFile(fs.TextFile ioTextFile) {
late String contents;
try {
contents = ioTextFile.readString();
} on FormatException {
throw 'non-UTF8 data in $ioTextFile';
}
return contents;
}
List<License>? _internalLicenses;
@override
License extractInternalLicense() {
_internalLicenses ??= determineLicensesFor(_contents, name, parent, origin: io.fullName);
if (_internalLicenses == null || _internalLicenses!.isEmpty) {
throw 'tried to extract a license from $this but there is nothing here';
}
if (_internalLicenses!.length > 1) {
throw 'tried to extract a license from $this but there are multiple licenses in this file';
}
return _internalLicenses!.single;
}
@override
Iterable<Assignment> assignLicenses() {
_internalLicenses ??= determineLicensesFor(_contents, name, parent, origin: io.fullName);
final List<License>? licenses = _internalLicenses;
if (licenses != null && licenses.isNotEmpty) {
return licenses.map((License license) => license.assignLicenses(io.fullName, parent!));
}
return super.assignLicenses();
}
}
class _RepositoryBinaryFile extends _RepositoryLicensedFile {
_RepositoryBinaryFile(super.parent, super.io);
@override
Iterable<Assignment> assignLicenses() {
final List<License> licenses = parent!.nearestLicensesFor(name);
if (licenses.isEmpty) {
throw 'no license file found in scope for ${io.fullName}';
}
return licenses.map((License license) => license.assignLicenses(io.fullName, parent!));
}
}
// LICENSES
abstract class _RepositoryLicenseFile extends _RepositoryFile {
_RepositoryLicenseFile(super.parent, fs.TextFile super.io);
// returns any licenses that apply specifically to the file named "name"
List<License> licensesFor(String name) => licenses;
// returns the license that applies to files looking for a license of the given type
License? licenseOfType(LicenseType type);
// returns the license that applies to files looking for a license of the given name
License? licenseWithName(String name);
License? get defaultLicense;
List<License> get licenses;
}
abstract class _RepositorySingleLicenseFile extends _RepositoryLicenseFile {
_RepositorySingleLicenseFile(super.parent, super.io, this.license);
final License license;
@override
License? licenseWithName(String name) {
if (this.name == name) {
return license;
}
return null;
}
@override
License? licenseOfType(LicenseType type) {
assert(type != LicenseType.unknown);
if (type == license.type) {
return license;
}
return null;
}
@override
License get defaultLicense => license;
@override
List<License> get licenses => <License>[license];
}
class _RepositoryGeneralSingleLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryGeneralSingleLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
static License _parseLicense(fs.TextFile io) {
final String body = io.readString();
int start = 0;
Match? match;
while ((match = licenseHeaders.matchAsPrefix(body, start)) != null) {
assert(match!.end > start);
start = match!.end; // https://github.com/dart-lang/sdk/issues/50264
}
return License.fromBodyAndName(body.substring(start), io.name, origin: io.fullName);
}
}
// Avoid using this unless the license file has multiple licenses in a weird mishmash.
// For example, the RapidJSON license which mixes BSD and MIT in somewhat confusing ways
// (e.g. having the copyright for one above the terms for the other and so on).
class _RepositoryOpaqueLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryOpaqueLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, License.unique(io.readString(), LicenseType.unknown, origin: io.fullName, yesWeKnowWhatItLooksLikeButItIsNot: true));
}
class _RepositoryReadmeIjgFile extends _RepositorySingleLicenseFile {
_RepositoryReadmeIjgFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
// The message we are required to include in our output.
//
// We include it by just including the whole license.
static const String _message = 'this software is based in part on the work of the Independent JPEG Group';
// The license text that says we should output _message.
//
// We inject _message into it, munged such that each space character can also
// match a newline, so that if the license wraps the text, it still matches.
static final RegExp _pattern = RegExp(
r'Permission is hereby granted to use, copy, modify, and distribute this\n'
r'software \(or portions thereof\) for any purpose, without fee, subject to these\n'
r'conditions:\n'
r'\(1\) If any part of the source code for this software is distributed, then this\n'
r'README file must be included, with this copyright and no-warranty notice\n'
r'unaltered; and any additions, deletions, or changes to the original files\n'
r'must be clearly indicated in accompanying documentation\.\n'
r'\(2\) If only executable code is distributed, then the accompanying\n'
r'documentation must state that "' '${_message.replaceAll(" ", "[ \n]+")}' r'"\.\n'
r'\(3\) Permission for use of this software is granted only if the user accepts\n'
r'full responsibility for any undesirable consequences; the authors accept\n'
r'NO LIABILITY for damages of any kind\.\n',
);
static License _parseLicense(fs.TextFile io) {
final String body = io.readString();
if (!body.contains(_pattern)) {
throw 'unexpected contents in IJG README';
}
return License.message(body, LicenseType.ijg, origin: io.fullName);
}
@override
License? licenseWithName(String name) {
if (this.name == name) {
return license;
}
return null;
}
}
class _RepositoryDartLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryDartLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
static final RegExp _pattern = RegExp(
r'(Copyright (?:.|\n)+)$',
);
static License _parseLicense(fs.TextFile io) {
final Match? match = _pattern.firstMatch(io.readString());
if (match == null || match.groupCount != 1) {
throw 'unexpected Dart license file contents';
}
return License.template(match.group(1)!, LicenseType.bsd, origin: io.fullName);
}
}
class _RepositoryLibPngLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryLibPngLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, License.message(io.readString(), LicenseType.libpng, origin: io.fullName)) {
_verifyLicense(io);
}
static void _verifyLicense(fs.TextFile io) {
final String contents = io.readString();
if (!contents.contains(RegExp('COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:?')) ||
!contents.contains('png')) {
throw 'unexpected libpng license file contents:\n----8<----\n$contents\n----<8----';
}
}
}
class _RepositoryLibJpegTurboLicenseFile extends _RepositoryLicenseFile {
_RepositoryLibJpegTurboLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io) {
_parseLicense(io);
}
static final RegExp _pattern = RegExp(
r'libjpeg-turbo is covered by three compatible BSD-style open source licenses:\n'
r'\n'
r'- The IJG \(Independent JPEG Group\) License, which is listed in\n'
r' \[README\.ijg\]\(README\.ijg\)\n'
r'\n'
r' This license applies to the libjpeg API library and associated programs\n'
r' \(any code inherited from libjpeg, and any modifications to that code\.\)\n'
r'\n'
r'- The Modified \(3-clause\) BSD License, which is listed in\n'
r' \[turbojpeg\.c\]\(turbojpeg\.c\)\n'
r'\n'
r' This license covers the TurboJPEG API library and associated programs\.\n'
r'\n'
r'- The zlib License, which is listed in \[simd/jsimdext\.inc\]\(simd/jsimdext\.inc\)\n'
r'\n'
r' This license is a subset of the other two, and it covers the libjpeg-turbo\n'
r' SIMD extensions\.\n'
);
static void _parseLicense(fs.TextFile io) {
final String body = io.readString();
if (!body.contains(_pattern)) {
throw 'unexpected contents in libjpeg-turbo LICENSE';
}
}
@override
License? licenseWithName(String name) {
return null;
}
@override
License? licenseOfType(LicenseType type) {
return null;
}
@override
License? get defaultLicense => null;
List<License>? _licenses;
@override
List<License> get licenses {
if (_licenses == null) {
final _RepositoryLicenseFile readme = parent!.getChildByName('README.ijg') as _RepositoryReadmeIjgFile;
final _RepositorySourceFile main = parent!.getChildByName('turbojpeg.c') as _RepositorySourceFile;
final _RepositoryDirectory simd = parent!.getChildByName('simd') as _RepositoryDirectory;
final _RepositorySourceFile zlib = simd.getChildByName('jsimdext.inc') as _RepositorySourceFile;
_licenses = <License>[];
_licenses!.addAll(readme.licenses);
_licenses!.add(main.extractInternalLicense());
_licenses!.add(zlib.extractInternalLicense());
}
return _licenses!;
}
}
class _RepositoryFreetypeLicenseFile extends _RepositoryLicenseFile {
_RepositoryFreetypeLicenseFile(super.parent, super.io)
: _target = _parseLicense(io);
static final RegExp _pattern = RegExp(
r'FREETYPE LICENSES\n'
r'-----------------\n'
r'\n'
r'The FreeType 2 font engine is copyrighted work and cannot be used\n'
r'legally without a software license\. In order to make this project\n'
r'usable to a vast majority of developers, we distribute it under two\n'
r'mutually exclusive open-source licenses\.\n'
r'\n'
r'This means that \*you\* must choose \*one\* of the two licenses described\n'
r'below, then obey all its terms and conditions when using FreeType 2 in\n'
r'any of your projects or products\.\n'
r'\n'
r' - The FreeType License, found in the file `docs/(FTL\.TXT)`, which is\n'
r' similar to the original BSD license \*with\* an advertising clause\n'
r' that forces you to explicitly cite the FreeType project in your\n'
r" product's documentation\. All details are in the license file\.\n"
r" This license is suited to products which don't use the GNU General\n"
r' Public License\.\n'
r'\n'
r' Note that this license is compatible to the GNU General Public\n'
r' License version 3, but not version 2\.\n'
r'\n'
r' - The GNU General Public License version 2, found in\n'
r' `docs/GPLv2\.TXT` \(any later version can be used also\), for\n'
r' programs which already use the GPL\. Note that the FTL is\n'
r' incompatible with GPLv2 due to its advertisement clause\.\n'
r'\n'
r'The contributed BDF and PCF drivers come with a license similar to\n'
r'that of the X Window System\. It is compatible to the above two\n'
r'licenses \(see files `src/bdf/README` and `src/pcf/README`\)\. The same\n'
r'holds for the source code files `src/base/fthash\.c` and\n'
r'`include/freetype/internal/fthash\.h`; they wer part of the BDF driver\n'
r'in earlier FreeType versions\.\n'
r'\n'
r'The gzip module uses the zlib license \(see `src/gzip/zlib\.h`\) which\n'
r'too is compatible to the above two licenses\.\n'
r'\n'
r'The MD5 checksum support \(only used for debugging in development\n'
r'builds\) is in the public domain\.\n'
r'\n*'
r'--- end of LICENSE\.TXT ---\n*$'
);
static String _parseLicense(fs.TextFile io) {
final Match? match = _pattern.firstMatch(io.readString());
if (match == null || match.groupCount != 1) {
throw 'unexpected Freetype license file contents';
}
return match.group(1)!;
}
final String _target;
List<License>? _targetLicense;
void _warmCache() {
if (parent != null && _targetLicense == null) {
final License? license = parent!.nearestLicenseWithName(_target);
if (license == null) {
throw 'Could not find license in Freetype directory. Make sure $_target is not excluded from consideration.';
}
_targetLicense = <License>[license];
}
}
@override
License? licenseOfType(LicenseType type) => null;
@override
License? licenseWithName(String name) => null;
@override
License get defaultLicense {
_warmCache();
return _targetLicense!.single;
}
@override
List<License> get licenses {
_warmCache();
return _targetLicense ?? const <License>[];
}
}
class _RepositoryIcuLicenseFile extends _RepositorySingleLicenseFile {
factory _RepositoryIcuLicenseFile(_RepositoryDirectory parent, fs.TextFile io) {
final Match? match = _pattern.firstMatch(_fixup(io.readString()));
if (match == null) {
throw 'could not parse ICU license file';
}
const int groupCount = 22;
assert(match.groupCount == groupCount, 'ICU: expected $groupCount groups, but got ${match.groupCount}');
const int timeZoneGroup = 18;
if (match.group(timeZoneGroup)!.contains(copyrightMentionPattern)) {
throw 'ICU: unexpected copyright in time zone database group\n:${match.group(timeZoneGroup)}';
}
if (!match.group(timeZoneGroup)!.contains('7. Database Ownership')) {
throw 'ICU: unexpected text in time zone database group\n:${match.group(timeZoneGroup)}';
}
const int gplGroup1 = 20;
const int gplGroup2 = 21;
if (!match.group(gplGroup1)!.contains(gplExceptionExplanation1) || !match.group(gplGroup2)!.contains(gplExceptionExplanation2)) {
throw 'ICU: did not find GPL exception in GPL-licensed files';
}
const Set<int> skippedGroups = <int>{ timeZoneGroup, gplGroup1, gplGroup2 };
return _RepositoryIcuLicenseFile._(
parent,
io,
License.template(match.group(2)!, LicenseType.bsd, origin: io.fullName),
License.fromMultipleBlocks(
match.groups(
Iterable<int>
.generate(groupCount, (int index) => index + 1)
.where((int index) => !skippedGroups.contains(index))
.toList()
).cast<String>(),
LicenseType.icu,
origin: io.fullName,
yesWeKnowWhatItLooksLikeButItIsNot: true,
),
);
}
_RepositoryIcuLicenseFile._(_RepositoryDirectory parent, fs.TextFile io, this.template, License license)
: super(parent, io, license);
static final RegExp _pattern = RegExp(
r'^(UNICODE, INC\. LICENSE AGREEMENT - DATA FILES AND SOFTWARE\n+' // group
r'See Terms of Use (?:.|\n)+?'
r'COPYRIGHT AND PERMISSION NOTICE\n+'
r'Copyright.+\n'
r'Distributed under the Terms of Use in .+\n+'
r')(Permission is hereby granted(?:.|\n)+?)' // template group
r'\n+-+\n+'
r'(Third-Party Software Licenses\n+' // group
r'This section contains third-party software notices and/or additional\n'
r'terms for licensed third-party software components included within ICU\n'
r'libraries\.\n+)'
r'-+\n+'
r'(ICU License - ICU 1\.8\.1 to ICU 57.1[ \n]+?' // group
r'COPYRIGHT AND PERMISSION NOTICE\n+'
r'Copyright (?:.|\n)+?)\n+'
r'-+\n+'
r'(Chinese/Japanese Word Break Dictionary Data \(cjdict\.txt\)\n+)' // group
r'( # The Google Chrome software developed by Google is licensed under\n?' // group
r' # the BSD license\. Other software included in this distribution is\n?'
r' # provided under other licenses, as set forth below\.\n'
r' #\n'
r' # The BSD License\n'
r' # http://opensource\.org/licenses/bsd-license\.php\n'
r' # +Copyright(?:.|\n)+?)\n'
r' #\n'
r' #\n'
r'( # The word list in cjdict.txt are generated by combining three word lists\n?' // group
r' # listed below with further processing for compound word breaking\. The\n?'
r' # frequency is generated with an iterative training against Google web\n?'
r' # corpora\.\n'
r' #\n' // if this section is taken out, make sure to remove the cjdict.txt exclusion in paths.dart
r' # \* Libtabe \(Chinese\)\n'
r' # - https://sourceforge\.net/project/\?group_id=1519\n'
r' # - Its license terms and conditions are shown below\.\n'
r' #\n'
r' # \* IPADIC \(Japanese\)\n'
r' # - http://chasen\.aist-nara\.ac\.jp/chasen/distribution\.html\n'
r' # - Its license terms and conditions are shown below\.\n'
r' #\n)'
r' # ---------COPYING\.libtabe ---- BEGIN--------------------\n'
r' #\n'
r' # +/\*\n'
r'( # +\* Copyright (?:.|\n)+?)\n' // group
r' # +\*/\n'
r' #\n'
r' # +/\*\n'
r'( # +\* Copyright (?:.|\n)+?)\n' // group
r' # +\*/\n'
r' #\n'
r'( # +Copyright (?:.|\n)+?)\n' // group
r' #\n'
r' # +---------------COPYING\.libtabe-----END--------------------------------\n'
r' #\n'
r' #\n'
r' # +---------------COPYING\.ipadic-----BEGIN-------------------------------\n'
r' #\n'
r'( # +Copyright (?:.|\n)+?)\n' // group
r' #\n'
r' # +---------------COPYING\.ipadic-----END----------------------------------\n+'
r'-+\n+'
r'(Lao Word Break Dictionary Data \(laodict\.txt\)\n)' // group
r'\n' // if this section is taken out, make sure to remove the laodict.txt exclusion in paths.dart
r'( # +Copyright(?:.|\n)+?)' // group
r'( # +This file is derived(?:.|\n)+?)\n'
r'\n'
r'-+\n'
r'\n'
r'(Burmese Word Break Dictionary Data \(burmesedict\.txt\)\n)' // group
r'\n' // if this section is taken out, make sure to remove the burmesedict.txt exclusion in paths.dart
r'( # +Copyright(?:.|\n)+?)\n' // group
r' # +-+\n'
r'( # +Copyright(?:.|\n)+?)\n' // group
r' # +-+\n+'
r'-+\n+'
r'( *Time Zone Database\n'
r'(?:.|\n)+)\n' // group (not really a license -- excluded)
r'\n'
r'-+\n'
r'\n'
r'(Google double-conversion\n' // group
r'\n'
r'Copyright(?:.|\n)+)\n'
r'\n'
r'-+\n'
r'\n'
r'(File: aclocal\.m4 \(only for ICU4C\)\n' // group (excluded)
r'Section: pkg\.m4 - Macros to locate and utilise pkg-config\.\n+'
r'Copyright (?:.|\n)+?)\n'
r'\n'
r'-+\n'
r'\n'
r'(File: config\.guess \(only for ICU4C\)\n+' // group (excluded)
r'This file is free software(?:.|\n)+?)\n'
r'\n'
r'-+\n'
r'\n'
r'(File: install-sh \(only for ICU4C\)\n+' // group
r'Copyright(?:.|\n)+)',
);
static const String gplExceptionExplanation1 =
'As a special exception to the GNU General Public License, if you\n'
'distribute this file as part of a program that contains a\n'
'configuration script generated by Autoconf, you may include it under\n'
'the same distribution terms that you use for the rest of that\n'
'program.\n'
'\n'
'\n'
'(The condition for the exception is fulfilled because\n'
'ICU4C includes a configuration script generated by Autoconf,\n'
'namely the `configure` script.)';
static const String gplExceptionExplanation2 =
'As a special exception to the GNU General Public License, if you\n'
'distribute this file as part of a program that contains a\n'
'configuration script generated by Autoconf, you may include it under\n'
'the same distribution terms that you use for the rest of that\n'
'program. This Exception is an additional permission under section 7\n'
'of the GNU General Public License, version 3 ("GPLv3").\n'
'\n'
'\n'
'(The condition for the exception is fulfilled because\n'
'ICU4C includes a configuration script generated by Autoconf,\n'
'namely the `configure` script.)';
// Fixes an error in the license's formatting that our reformatter wouldn't be
// able to figure out on its own and which would otherwise completely mess up
// the reformatting of this license file.
static String _fixup(String license) {
return license.replaceAll(
' # * Sinica. All rights reserved.',
' # * Sinica. All rights reserved.',
);
}
final License template;
@override
License? licenseOfType(LicenseType type) {
if (type == LicenseType.defaultTemplate) {
return template;
}
return super.licenseOfType(type);
}
}
class _RepositoryCxxStlDualLicenseFile extends _RepositoryLicenseFile {
_RepositoryCxxStlDualLicenseFile(super.parent, super.io)
: _licenses = _parseLicenses(io);
static final RegExp _pattern = RegExp(
r'^'
r'==============================================================================\n'
r'The LLVM Project is under the Apache License v2\.0 with LLVM Exceptions:\n'
r'==============================================================================\n'
r'\n('
r' *Apache License\n'
r' *Version 2.0, January 2004\n'
r' *http://www.apache.org/licenses/\n'
r'\n'
r'.+?)\n+'
r'---- LLVM Exceptions to the Apache 2.0 License ----'
r'.+?'
r'==============================================================================\n'
r'Software from third parties included in the LLVM Project:\n'
r'==============================================================================\n'
r'The LLVM Project contains third party software which is under different license\n'
r'terms\. All such code will be identified clearly using at least one of two\n'
r'mechanisms:\n'
r'1\) It will be in a separate directory tree with its own `LICENSE\.txt` or\n'
r' *`LICENSE` file at the top containing the specific license and restrictions\n'
r' *which apply to that software, or\n'
r'2\) It will contain specific license and restriction terms at the top of every\n'
r' *file\.\n'
r'\n'
r'==============================================================================\n'
r'Legacy LLVM License \(https://llvm\.org/docs/DeveloperPolicy\.html#legacy\):\n'
r'==============================================================================\n'
r'\n'
r'The libc\+\+(?:abi)? library is dual licensed under both the University of Illinois\n'
r'"BSD-Like" license and the MIT license\. *As a user of this code you may choose\n'
r'to use it under either license\. *As a contributor, you agree to allow your code\n'
r'to be used under both\.\n'
r'\n'
r'Full text of the relevant licenses is included below\.\n'
r'\n'
r'==============================================================================\n'
r'\n'
r'University of Illinois/NCSA\n'
r'Open Source License\n'
r'\n'
r'(Copyright \(c\) 2009-2019 by the contributors listed in CREDITS\.TXT\n'
r'\n'
r'All rights reserved\.\n'
r'\n'
r'Developed by:\n'
r'\n'
r' *LLVM Team\n'
r'\n'
r' *University of Illinois at Urbana-Champaign\n'
r'\n'
r' *http://llvm\.org\n'
r'\n'
r'Permission is hereby granted, free of charge, to any person obtaining a copy of\n'
r'this software and associated documentation files \(the "Software"\), to deal with\n'
r'the Software without restriction, including without limitation the rights to\n'
r'use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\n'
r'of the Software, and to permit persons to whom the Software is furnished to do\n'
r'so, subject to the following conditions:\n'
r'\n'
r' *\* Redistributions of source code must retain the above copyright notice,\n'
r' *this list of conditions and the following disclaimers\.\n'
r'\n'
r' *\* Redistributions in binary form must reproduce the above copyright notice,\n'
r' *this list of conditions and the following disclaimers in the\n'
r' *documentation and/or other materials provided with the distribution\.\n'
r'\n'
r' *\* Neither the names of the LLVM Team, University of Illinois at\n'
r' *Urbana-Champaign, nor the names of its contributors may be used to\n'
r' *endorse or promote products derived from this Software without specific\n'
r' *prior written permission\.\n'
r'\n'
r'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
r'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n'
r'FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\. IN NO EVENT SHALL THE\n'
r'CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
r'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
r'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS WITH THE\n'
r'SOFTWARE\.)\n*'
r'==============================================================================\n*'
r'(Copyright \(c\) 2009-2014 by the contributors listed in CREDITS\.TXT\n'
r'\n'
r'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
r'of this software and associated documentation files \(the "Software"\), to deal\n'
r'in the Software without restriction, including without limitation the rights\n'
r'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
r'copies of the Software, and to permit persons to whom the Software is\n'
r'furnished to do so, subject to the following conditions:\n'
r'\n'
r'The above copyright notice and this permission notice shall be included in\n'
r'all copies or substantial portions of the Software\.\n'
r'\n'
r'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
r'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
r'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\. IN NO EVENT SHALL THE\n'
r'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
r'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
r'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
r'THE SOFTWARE\.)\n*'
r'$',
dotAll: true,
);
static List<License> _parseLicenses(fs.TextFile io) {
final Match? match = _pattern.firstMatch(io.readString());
if (match == null) {
throw 'unexpected license file contents';
}
if (match.groupCount != 3) {
throw 'internal error; match count inconsistency\nRemainder:[[${match.input.substring(match.end)}]]';
}
return <License>[
// License.fromBodyAndType(match.group(1), LicenseType.apache), // the exception says we can ignore this
License.fromBodyAndType(match.group(2)!, LicenseType.bsd, origin: io.fullName),
License.fromBodyAndType(match.group(3)!, LicenseType.mit, origin: io.fullName),
];
}
final List<License> _licenses;
@override
License licenseOfType(LicenseType type) {
throw 'tried to look up a dual-license license by type ("$type")';
}
@override
License licenseWithName(String name) {
throw 'tried to look up a dual-license license by name ("$name")';
}
@override
License get defaultLicense => _licenses[0];
@override
List<License> get licenses => _licenses;
}
class _RepositoryKhronosLicenseFile extends _RepositoryLicenseFile {
_RepositoryKhronosLicenseFile(super.parent, super.io)
: _licenses = _parseLicenses(io);
static final RegExp _pattern = RegExp(
r'^(Copyright .+?)\n'
r'SGI FREE SOFTWARE LICENSE B[^\n]+\n\n'
r'(Copyright .+?)$',
dotAll: true,
);
static List<License> _parseLicenses(fs.TextFile io) {
final Match? match = _pattern.firstMatch(io.readString());
if (match == null || match.groupCount != 2) {
throw 'unexpected Khronos license file contents';
}
return <License>[
License.fromBodyAndType(match.group(1)!, LicenseType.mit, origin: io.fullName),
License.fromBodyAndType(match.group(2)!, LicenseType.mit, origin: io.fullName),
];
}
final List<License> _licenses;
@override
License licenseOfType(LicenseType type) {
throw 'tried to look up a combination license by type ("$type")';
}
@override
License licenseWithName(String name) {
throw 'tried to look up a combination license by name ("$name")';
}
@override
License get defaultLicense {
throw 'there is no default Khronos license';
}
@override
List<License> get licenses => _licenses;
}
/// The BoringSSL license file.
///
/// This file contains a bunch of different licenses, but other files
/// refer to it as if it was a monolithic license so we sort of have
/// to treat the whole thing as a MultiLicense.
class _RepositoryOpenSSLLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryOpenSSLLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
static final RegExp _pattern = RegExp(
// advice is to skip the first 27 lines of this file in the LICENSE file
r'^BoringSSL is a fork of OpenSSL. As such, .+?'
r'The following are Google-internal bug numbers where explicit permission from\n'
r'some authors is recorded for use of their work\. \(This is purely for our own\n'
r'record keeping\.\)\n+'
r'[0-9+ \n]+\n+'
r'(' // 1
r' *OpenSSL License\n'
r' *---------------\n+)'
r'(.+?)\n+' // 2
r'(' // 3
r' *Original SSLeay License\n'
r' *-----------------------\n+)'
r'(.+?)\n+' // 4
r'( *ISC license used for completely new code in BoringSSL:\n+)' // 5
r'(.+?)\n+' // 6
r'( *The code in third_party/fiat carries the MIT license:\n+)' // 7
r'(.+?)\n+' // 8
r'(' // 9
r' *Licenses for support code\n'
r' *-------------------------\n+)'
r'(.+?)\n+' // 10
r'(BoringSSL uses the Chromium test infrastructure to run a continuous build,\n' // 11
r'trybots etc\. The scripts which manage this, and the script for generating build\n'
r'metadata, are under the Chromium license\. Distributing code linked against\n'
r'BoringSSL does not trigger this license\.)\n+'
r'(.+?)\n+$', // 12
dotAll: true,
);
static License _parseLicense(fs.TextFile io) {
final Match? match = _pattern.firstMatch(io.readString());
if (match == null) {
throw 'Failed to match OpenSSL license pattern.';
}
assert(match.groupCount == 12);
return License.fromMultipleBlocks(
List<String>.generate(match.groupCount, (int index) => match.group(index + 1)!).toList(),
LicenseType.openssl,
origin: io.fullName,
authors: 'The OpenSSL Project Authors',
yesWeKnowWhatItLooksLikeButItIsNot: true, // looks like BSD, but...
);
}
}
class _RepositoryFuchsiaSdkLinuxLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryFuchsiaSdkLinuxLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
static const String _pattern = 'The majority of files in this project use the Apache 2.0 License.\n'
'There are a few exceptions and their license can be found in the source.\n'
'Any license deviations from Apache 2.0 are "more permissive" licenses.\n';
static License _parseLicense(fs.TextFile io) {
final String body = io.readString();
if (!body.startsWith(_pattern)) {
throw 'unexpected Fuchsia license file contents';
}
return License.fromBodyAndType(body.substring(_pattern.length), LicenseType.apache, origin: io.fullName);
}
}
/// The BoringSSL license file.
///
/// This file contains a bunch of different licenses, but other files
/// refer to it as if it was a monolithic license so we sort of have
/// to treat the whole thing as a MultiLicense.
class _RepositoryVulkanApacheLicenseFile extends _RepositorySingleLicenseFile {
_RepositoryVulkanApacheLicenseFile(_RepositoryDirectory parent, fs.TextFile io)
: super(parent, io, _parseLicense(io));
static const String _prefix =
'The majority of files in this project use the Apache 2.0 License.\n'
'There are a few exceptions and their license can be found in the source.\n'
'Any license deviations from Apache 2.0 are "more permissive" licenses.\n'
"Any file without a license in it's source defaults to the repository Apache 2.0 License.\n"
'\n'
'===========================================================================================\n'
'\n';
static License _parseLicense(fs.TextFile io) {
final String body = io.readString();
if (!body.startsWith(_prefix)) {
throw 'Failed to match Vulkan Apache license prefix.';
}
return License.fromBody(body.substring(_prefix.length), origin: io.fullName);
}
}
// DIRECTORIES
typedef _Constructor = _RepositoryFile Function(_RepositoryDirectory parent, fs.TextFile);
class _RepositoryDirectory extends _RepositoryEntry implements LicenseSource {
_RepositoryDirectory(super.parent, fs.Directory super.io) {
crawl();
}
fs.Directory get ioDirectory => super.io as fs.Directory;
fs.Directory get rootDirectory => parent != null ? parent!.rootDirectory : ioDirectory;
final List<_RepositoryDirectory> _subdirectories = <_RepositoryDirectory>[];
final List<_RepositoryLicensedFile> _files = <_RepositoryLicensedFile>[];
final List<_RepositoryLicenseFile> _licenses = <_RepositoryLicenseFile>[];
static final List<fs.IoNode> _excluded = <fs.IoNode>[];
List<_RepositoryDirectory> get subdirectories => _subdirectories;
final Map<String,_RepositoryEntry> _childrenByName = <String,_RepositoryEntry>{};
void crawl() {
for (final fs.IoNode entry in ioDirectory.walk) {
if (shouldRecurse(entry)) {
assert(!_childrenByName.containsKey(entry.name));
if (entry is fs.Directory) {
final _RepositoryDirectory child = createSubdirectory(entry);
_subdirectories.add(child);
_childrenByName[child.name] = child;
} else if (entry is fs.File) {
try {
final _RepositoryFile child = createFile(entry);
if (child is _RepositoryLicensedFile) {
_files.add(child);
} else {
assert(child is _RepositoryLicenseFile);
_licenses.add(child as _RepositoryLicenseFile);
}
_childrenByName[child.name] = child;
} catch (error, stack) {
throw 'failed to handle $entry\n$error\nOriginal stack:\n$stack';
}
} else {
assert(entry is fs.Link);
}
} else {
_excluded.add(entry);
}
}
for (final _RepositoryDirectory child in virtualSubdirectories) {
_subdirectories.add(child);
_childrenByName[child.name] = child;
}
}
// Override this to add additional child directories that do not represent a
// direct child of this directory's filesystem node.
List<_RepositoryDirectory> get virtualSubdirectories => <_RepositoryDirectory>[];
bool shouldRecurse(fs.IoNode entry) {
if (entry is fs.File) {
if (skippedCommonFiles.contains(entry.name)) {
return false;
}
if (skippedCommonExtensions.contains(path.extension(entry.name))) {
return false;
}
} else if (entry is fs.Directory) {
if (skippedCommonDirectories.contains(entry.name)) {
return false;
}
} else {
throw 'unexpected entry type ${entry.runtimeType}: ${entry.fullName}';
}
final String target = path.relative(entry.fullName, from: rootDirectory.fullName);
if (skippedPaths.contains(target)) {
return false;
}
for (final Pattern pattern in skippedFilePatterns) {
if (target.contains(pattern)) {
return false;
}
}
return true;
}
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'third_party') {
return _RepositoryGenericThirdPartyDirectory(this, entry);
}
return _RepositoryDirectory(this, entry);
}
// the bit at the beginning excludes files like "license.py".
static final RegExp _licenseNamePattern = RegExp(r'^(?!.*\.py$)(?!.*(?:no|update)-copyright)(?!.*mh-bsd-gcc).*\b_*(?:license(?!\.html)|copying|copyright|notice|l?gpl|GPLv2|bsd|mit|mpl?|ftl|Apache)_*\b', caseSensitive: false);
static const Map<String, _Constructor> _specialCaseFiles = <String, _Constructor>{
'/flutter/third_party/boringssl/src/LICENSE': _RepositoryOpenSSLLicenseFile.new,
'/flutter/third_party/freetype2/LICENSE.TXT': _RepositoryFreetypeLicenseFile.new,
'/flutter/third_party/icu/LICENSE': _RepositoryIcuLicenseFile.new,
'/flutter/third_party/inja/third_party/include/nlohmann/json.hpp': _RepositoryInjaJsonFile.new,
'/flutter/third_party/libjpeg-turbo/src/LICENSE': _RepositoryLibJpegTurboLicenseFile.new,
'/flutter/third_party/libjpeg-turbo/src/README.ijg': _RepositoryReadmeIjgFile.new,
'/flutter/third_party/libpng/LICENSE': _RepositoryLibPngLicenseFile.new,
'/flutter/third_party/rapidjson/LICENSE': _RepositoryOpaqueLicenseFile.new,
'/flutter/third_party/rapidjson/license.txt': _RepositoryOpaqueLicenseFile.new,
'/flutter/third_party/vulkan-deps/vulkan-validation-layers/src/LICENSE.txt': _RepositoryVulkanApacheLicenseFile.new,
'/fuchsia/sdk/linux/LICENSE.vulkan': _RepositoryFuchsiaSdkLinuxLicenseFile.new,
'/fuchsia/sdk/mac/LICENSE.vulkan': _RepositoryFuchsiaSdkLinuxLicenseFile.new,
'/third_party/dart/LICENSE': _RepositoryDartLicenseFile.new,
'/third_party/khronos/LICENSE': _RepositoryKhronosLicenseFile.new,
'/third_party/libcxx/LICENSE.TXT': _RepositoryCxxStlDualLicenseFile.new,
'/third_party/libcxxabi/LICENSE.TXT': _RepositoryCxxStlDualLicenseFile.new,
};
_RepositoryFile createFile(fs.IoNode entry) {
final String key = '/${path.relative(entry.fullName, from: rootDirectory.fullName)}';
final _Constructor? constructor = _specialCaseFiles[key];
if (entry is fs.TextFile) {
if (constructor != null) {
return constructor(this, entry);
}
if (entry.name.contains(_licenseNamePattern)) {
return _RepositoryGeneralSingleLicenseFile(this, entry);
}
return _RepositorySourceFile(this, entry);
}
return _RepositoryBinaryFile(this, entry as fs.File);
}
int get count => _files.length + _subdirectories.fold<int>(0, (int count, _RepositoryDirectory child) => count + child.count);
bool _canGoUp() {
assert(parent != null || isLicenseRoot);
return isLicenseRootException || (!isLicenseRoot && !parent!.subdirectoriesAreLicenseRoots);
}
@override
List<License> nearestLicensesFor(String name) {
if (_licenses.isEmpty) {
if (_canGoUp()) {
return parent!.nearestLicensesFor('${io.name}/$name');
}
return const <License>[];
}
return _licenses.expand((_RepositoryLicenseFile license) {
return license.licensesFor(name);
}).toList();
}
final Map<LicenseType, License?> _nearestLicenseOfTypeCache = <LicenseType, License?>{};
/// Searches the current directory, all parent directories up to the license
/// root, and all their descendants, for a license of the specified type.
@override
License? nearestLicenseOfType(LicenseType type) {
return _nearestLicenseOfTypeCache.putIfAbsent(type, () {
final License? result = _localLicenseWithType(type);
if (result != null) {
return result;
}
if (_canGoUp()) {
return parent!.nearestLicenseOfType(type);
}
return _fullWalkDownForLicenseWithType(type);
});
}
/// Searches the current directory for licenses of the specified type.
License? _localLicenseWithType(LicenseType type) {
final List<License> licenses = _licenses.expand((_RepositoryLicenseFile license) {
final License? result = license.licenseOfType(type);
if (result != null) {
return <License>[result];
}
return const <License>[];
}).toList();
if (licenses.length > 1) {
print('unexpectedly found multiple matching licenses in $name of type $type');
return null;
}
if (licenses.isNotEmpty) {
return licenses.single;
}
return null;
}
/// Searches all subdirectories (depth-first) for a license of the specified type.
License? _fullWalkDownForLicenseWithType(LicenseType type) {
for (final _RepositoryDirectory directory in _subdirectories) {
if (directory._canGoUp()) { // avoid crawling into other license scopes
final License? result = directory._localLicenseWithType(type) ?? directory._fullWalkDownForLicenseWithType(type);
if (result != null) {
return result;
}
}
}
return null;
}
final Map<String, License?> _nearestLicenseWithNameCache = <String, License?>{};
@override
License? nearestLicenseWithName(String name, {String? authors}) {
assert(!name.contains('\x00'));
assert(authors == null || !authors.contains('\x00'));
assert(authors == null || authors != '${null}');
final License? result = _nearestLicenseWithNameCache.putIfAbsent('$name\x00$authors', () {
final License? result = _localLicenseWithName(name, authors: authors);
if (result != null) {
return result;
}
if (_canGoUp()) {
return parent!.nearestLicenseWithName(name, authors: authors);
}
return _fullWalkDownForLicenseWithName(name, authors: authors)
?? (authors != null ? parent?._fullWalkUpForLicenseWithName(name, authors: authors) : null);
});
return result;
}
License? _localLicenseWithName(String name, { String? authors }) {
final _RepositoryEntry? entry = _childrenByName[name];
License? license;
if (entry is _RepositoryLicensedFile) {
license = entry.extractInternalLicense();
} else if (entry is _RepositoryLicenseFile) {
license = entry.defaultLicense;
} else if (entry != null) {
if (authors == null) {
throw 'found "$name" in $this but it was a ${entry.runtimeType}';
}
}
if (license != null && authors != null && authors != license.authors) {
license = null;
}
return license;
}
License? _fullWalkUpForLicenseWithName(String name, { required String authors }) {
// When looking for a license specific to certain authors, we want to walk
// to the top of the local license root, then from there check all the
// ancestors and all the descendants.
//
// We check even the ancestors (on the other side of license root
// boundaries) for this because when we know which authors we're looking
// for, it's reasonable to look all the way up the tree (e.g. the Flutter
// Authors license is at the root, and is sometimes mentioned in various
// files deep inside third party directories).
return _localLicenseWithName(name, authors: authors) ??
parent?._fullWalkUpForLicenseWithName(name, authors: authors);
}
License? _fullWalkDownForLicenseWithName(String name, { String? authors }) {
for (final _RepositoryDirectory directory in _subdirectories) {
if (directory._canGoUp()) { // avoid crawling into other license scopes
final License? result = directory._localLicenseWithName(name, authors: authors)
?? directory._fullWalkDownForLicenseWithName(name, authors: authors);
if (result != null) {
return result;
}
}
}
return null;
}
/// Unless isLicenseRootException is true, we should not walk up the tree from
/// here looking for licenses.
bool get isLicenseRoot => parent == null;
/// Unless isLicenseRootException is true on a child, the child should not
/// walk up the tree to here looking for licenses.
bool get subdirectoriesAreLicenseRoots => false;
@override
String get libraryName {
if (isLicenseRoot || parent!.subdirectoriesAreLicenseRoots) {
return name;
}
if (parent!.parent == null) {
throw '$this is not a license root';
}
return parent!.libraryName;
}
/// Overrides isLicenseRoot and parent.subdirectoriesAreLicenseRoots for cases
/// where a directory contains license roots instead of being one. This
/// allows, for example, the expat third_party directory to contain a
/// subdirectory with expat while itself containing a BUILD file that points
/// to the LICENSE in the root of the repo.
bool get isLicenseRootException => false;
_RepositoryEntry getChildByName(String name) {
assert(_childrenByName.containsKey(name), 'missing $name in ${io.fullName}');
return _childrenByName[name]!;
}
Iterable<Assignment> assignLicenses(_Progress progress) {
final List<Assignment> result = <Assignment>[];
// Report licenses for files in this directory
for (final _RepositoryLicensedFile file in _files) {
try {
progress.label = '$file';
final Iterable<Assignment> licenses = file.assignLicenses();
assert(licenses.isNotEmpty);
result.addAll(licenses);
progress.advance(success: true);
} catch (e, stack) {
system.stderr.writeln('\nerror searching for copyright in: ${file.io}\n$e');
if (e is! String) {
system.stderr.writeln(stack);
}
system.stderr.writeln('\n');
progress.advance(success: false);
}
}
// Recurse to subdirectories
for (final _RepositoryDirectory directory in _subdirectories) {
result.addAll(directory.assignLicenses(progress));
}
return result;
}
int get fileCount {
int result = _files.length;
for (final _RepositoryDirectory directory in _subdirectories) {
result += directory.fileCount;
}
return result;
}
Iterable<_RepositoryLicensedFile> get _signatureFiles sync* {
for (final _RepositoryLicensedFile file in _files) {
yield file;
}
for (final _RepositoryDirectory directory in _subdirectories) {
if (directory.includeInSignature) {
yield* directory._signatureFiles;
}
}
}
Stream<List<int>> _signatureStream(List<_RepositoryLicensedFile> files) async* {
for (final _RepositoryLicensedFile file in files) {
yield file.io.fullName.codeUnits;
yield file.ioFile.readBytes()!;
}
}
/// Compute a signature representing a hash of all the licensed files within
/// this directory tree.
Future<String> get signature async {
final List<_RepositoryLicensedFile> allFiles = _signatureFiles.toList();
allFiles.sort((_RepositoryLicensedFile a, _RepositoryLicensedFile b) =>
a.io.fullName.compareTo(b.io.fullName));
final crypto.Digest digest = await crypto.md5.bind(_signatureStream(allFiles)).single;
return digest.bytes.map((int e) => e.toRadixString(16).padLeft(2, '0')).join();
}
/// True if this directory's contents should be included when computing the signature.
bool get includeInSignature => true;
@override
String get officialSourceLocation {
throw 'license requested source location for directory that should not need it';
}
}
class _RepositoryReachOutFile extends _RepositoryLicensedFile {
_RepositoryReachOutFile(super.parent, super.io, this.offset);
final int offset;
@override
Iterable<Assignment> assignLicenses() {
_RepositoryDirectory? directory = parent;
int index = offset;
while (index > 1) {
if (directory == null) {
break;
}
directory = directory.parent;
index -= 1;
}
return directory!.nearestLicensesFor(name).map((License license) => license.assignLicenses(io.fullName, parent!));
}
}
class _RepositoryReachOutDirectory extends _RepositoryDirectory {
_RepositoryReachOutDirectory(_RepositoryDirectory super.parent, super.io, this.reachOutFilenames, this.offset);
final Set<String> reachOutFilenames;
final int offset;
@override
_RepositoryFile createFile(fs.IoNode entry) {
if (reachOutFilenames.contains(entry.name)) {
return _RepositoryReachOutFile(this, entry as fs.File, offset);
}
return super.createFile(entry);
}
}
class _RepositoryInjaJsonFile extends _RepositorySourceFile {
_RepositoryInjaJsonFile(super.parent, super.io);
@override
License extractInternalLicense() {
throw '$this does not have a clearly extractable license';
}
static final RegExp _pattern = RegExp(
r'^(.*?)' // 1
r'Licensed under the MIT License <http://opensource\.org/licenses/MIT>\.\n'
r'SPDX-License-Identifier: MIT\n'
r'(Copyright \(c\) 2013-2019 Niels Lohmann <http://nlohmann\.me>\.)\n' // 2
r'\n'
r'(Permission is hereby granted, free of charge, to any person obtaining a copy\n' // 3
r'of this software and associated documentation files \(the "Software"\), to deal\n'
r'in the Software without restriction, including without limitation the rights\n'
r'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
r'copies of the Software, and to permit persons to whom the Software is\n'
r'furnished to do so, subject to the following conditions:\n'
r'\n'
r'The above copyright notice and this permission notice shall be included in all\n'
r'copies or substantial portions of the Software\.\n'
r'\n'
r'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
r'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
r'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\. IN NO EVENT SHALL THE\n'
r'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
r'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
r'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n'
r'SOFTWARE\.)\n'
r'(.*?)' // 4
r' \* Created by Evan Nemerson <evan@nemerson\.com>\n'
r' \*\n'
r' \* To the extent possible under law, the author\(s\) have dedicated all\n'
r' \* copyright and related and neighboring rights to this software to\n'
r' \* the public domain worldwide\. This software is distributed without\n'
r' \* any warranty\.\n'
r' \*\n'
r' \* For details, see <http://creativecommons\.org/publicdomain/zero/1\.0/>\.\n'
r' \* SPDX-License-Identifier: CC0-1\.0\n'
r'(.*?)' // 5
r'The code is distributed under the MIT license, (Copyright \(c\) 2009 Florian Loitsch\.)\n' // 6
r'(.*?)' // 7
r' @copyright (Copyright \(c\) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann\.de>)\n' // 8
r'(.*?)' // 9
r' `copyright` \| The copyright line for the library as string\.\n'
r'(.*?)' // 10
r' result\["copyright"\] = "\(C\) 2013-2020 Niels Lohmann";\n'
r'(.*)$', // 11
dotAll: true, // isMultiLine is false, so ^ and $ only match start and end.
);
@override
Iterable<Assignment> assignLicenses() {
if (_internalLicenses == null) {
final Match? match = _pattern.matchAsPrefix(_contents);
if (match == null) {
throw '${io.fullName} has changed contents.';
}
final String license = match.group(3)!;
_internalLicenses = match.groups(const <int>[ 2, 6, 8 ]).map<License>((String? copyright) {
assert(copyright!.contains('Copyright'));
return License.fromCopyrightAndLicense(copyright!, license, LicenseType.mit, origin: io.fullName);
}).toList();
assert(!match.groups(const <int>[ 1, 4, 5, 7, 9, 10, 11]).any((String? text) => text!.contains(copyrightMentionPattern)));
}
return _internalLicenses!.map((License license) => license.assignLicenses(io.fullName, parent!));
}
}
/// The `src/` directory created by gclient sync (a.k.a. buildroot).
///
/// This directory is the parent of the flutter/engine repository. The license
/// crawler begins its search starting from this directory and recurses down
/// from it.
///
/// This is not the root of the flutter/engine repository.
/// [_RepositoryFlutterDirectory] represents that.
class _EngineSrcDirectory extends _RepositoryDirectory {
_EngineSrcDirectory(fs.Directory io) : super(null, io);
@override
String get libraryName {
throw 'Package failed to determine library name.';
}
@override
bool get isLicenseRoot => true;
@override
bool get subdirectoriesAreLicenseRoots => false;
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'third_party') {
return _RepositoryRootThirdPartyDirectory(this, entry);
}
if (entry.name == 'flutter') {
return _RepositoryFlutterDirectory(this, entry);
}
if (entry.name == 'gpu') {
return _RepositoryGpuShimDirectory(this, entry);
}
if (entry.name == 'fuchsia') {
return _RepositoryFuchsiaDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
@override
List<_RepositoryDirectory> get virtualSubdirectories {
// Dart and Skia are updated more frequently than other third party
// libraries and is therefore represented as a separate top-level component.
final fs.Directory thirdPartyNode = findChildDirectory(ioDirectory, 'third_party')!;
final fs.Directory dartNode = findChildDirectory(thirdPartyNode, 'dart')!;
final fs.Directory flutterNode = findChildDirectory(ioDirectory, 'flutter')!;
final fs.Directory flutterThirdPartyNode = findChildDirectory(flutterNode, 'third_party')!;
final fs.Directory skiaNode = findChildDirectory(flutterThirdPartyNode, 'skia')!;
return <_RepositoryDirectory>[
_RepositoryDartDirectory(this, dartNode),
_RepositorySkiaDirectory(this, skiaNode),
];
}
}
class _RepositoryGenericThirdPartyDirectory extends _RepositoryDirectory {
_RepositoryGenericThirdPartyDirectory(_RepositoryDirectory super.parent, super.io);
@override
bool get subdirectoriesAreLicenseRoots => true;
}
class _RepositoryRootThirdPartyDirectory extends _RepositoryGenericThirdPartyDirectory {
_RepositoryRootThirdPartyDirectory(super.parent, super.io);
@override
bool shouldRecurse(fs.IoNode entry) {
return entry.name != 'dart' // handled as a virtual directory of the root
&& super.shouldRecurse(entry);
}
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'icu') {
return _RepositoryIcuDirectory(this, entry);
}
if (entry.name == 'zlib') {
return _RepositoryZLibDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryExpatDirectory extends _RepositoryDirectory {
_RepositoryExpatDirectory(_RepositoryDirectory super.parent, super.io);
@override
bool get isLicenseRootException => true;
@override
bool get subdirectoriesAreLicenseRoots => true;
}
class _RepositoryFreetypeDirectory extends _RepositoryDirectory {
_RepositoryFreetypeDirectory(_RepositoryDirectory super.parent, super.io);
@override
List<License> nearestLicensesFor(String name) {
final List<License> result = super.nearestLicensesFor(name);
if (result.isEmpty) {
final License? license = nearestLicenseWithName('LICENSE.TXT');
assert(license != null);
if (license != null) {
return <License>[license];
}
}
return result;
}
@override
License? nearestLicenseOfType(LicenseType type) {
if (type == LicenseType.freetype) {
final License? result = nearestLicenseWithName('FTL.TXT');
assert(result != null);
return result;
}
return super.nearestLicenseOfType(type);
}
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'src') {
return _RepositoryFreetypeSrcDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryFreetypeSrcDirectory extends _RepositoryDirectory {
_RepositoryFreetypeSrcDirectory(_RepositoryDirectory super.parent, super.io);
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'gzip') {
return _RepositoryFreetypeSrcGZipDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryFreetypeSrcGZipDirectory extends _RepositoryDirectory {
_RepositoryFreetypeSrcGZipDirectory(_RepositoryDirectory super.parent, super.io);
// advice was to make this directory's inffixed.h file (which has no license)
// use the license in zlib.h.
@override
List<License> nearestLicensesFor(String name) {
final License? zlib = nearestLicenseWithName('zlib.h');
assert(zlib != null);
if (zlib != null) {
return <License>[zlib];
}
return super.nearestLicensesFor(name);
}
@override
License? nearestLicenseOfType(LicenseType type) {
if (type == LicenseType.zlib) {
final License? result = nearestLicenseWithName('zlib.h');
assert(result != null);
return result;
}
return super.nearestLicenseOfType(type);
}
}
class _RepositoryIcuDirectory extends _RepositoryDirectory {
_RepositoryIcuDirectory(super.parent, super.io);
@override
_RepositoryFile createFile(fs.IoNode entry) {
if (entry.name == 'LICENSE') {
return _RepositoryIcuLicenseFile(this, entry as fs.TextFile);
}
return super.createFile(entry);
}
}
class _RepositoryFallbackRootCertificatesDirectory extends _RepositoryDirectory {
_RepositoryFallbackRootCertificatesDirectory(_RepositoryDirectory super.parent, super.io);
@override
String get officialSourceLocation {
final system.ProcessResult result = system.Process.runSync('git', <String>['rev-parse', 'HEAD'], workingDirectory: '$this');
if (result.exitCode != 0) {
throw 'Failed to run "git rev-parse HEAD"; got non-zero exit code ${result.exitCode}\nstdout:\n${result.stdout}\nstderr:\n${result.stderr}';
}
final String rev = result.stdout as String;
return 'https://dart.googlesource.com/sdk/+/$rev/third_party/fallback_root_certificates/';
}
}
class _RepositoryZLibDirectory extends _RepositoryDirectory {
_RepositoryZLibDirectory(_RepositoryDirectory super.parent, super.io);
// Some files in this directory refer to "MiniZip_info.txt".
// As best we can tell, that refers to a file that itself includes the
// exact same license text as in LICENSE.
@override
License? nearestLicenseWithName(String name, { String? authors }) {
if (name == 'MiniZip_info.txt') {
return super.nearestLicenseWithName('LICENSE', authors: authors)!;
}
return super.nearestLicenseWithName(name, authors: authors);
}
@override
License? nearestLicenseOfType(LicenseType type) {
if (type == LicenseType.zlib) {
return nearestLicenseWithName('LICENSE')!;
}
return super.nearestLicenseOfType(type);
}
}
class _RepositoryDartDirectory extends _RepositoryDirectory {
_RepositoryDartDirectory(_RepositoryDirectory super.parent, super.io);
@override
bool get isLicenseRoot => true;
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'third_party') {
return _RepositoryDartThirdPartyDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryDartThirdPartyDirectory extends _RepositoryGenericThirdPartyDirectory {
_RepositoryDartThirdPartyDirectory(super.parent, super.io);
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'fallback_root_certificates') {
return _RepositoryFallbackRootCertificatesDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositorySkiaDirectory extends _RepositoryDirectory {
_RepositorySkiaDirectory(_RepositoryDirectory super.parent, super.io);
@override
bool get isLicenseRoot => true;
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'third_party') {
return _RepositorySkiaThirdPartyDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositorySkiaThirdPartyDirectory extends _RepositoryGenericThirdPartyDirectory {
_RepositorySkiaThirdPartyDirectory(super.parent, super.io);
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'ktx') {
return _RepositoryReachOutDirectory(this, entry, const <String>{'ktx.h', 'ktx.cpp'}, 2);
}
if (entry.name == 'libmicrohttpd') {
return _RepositoryReachOutDirectory(this, entry, const <String>{'MHD_config.h'}, 2);
}
if (entry.name == 'libwebp') {
return _RepositorySkiaLibWebPDirectory(this, entry);
}
if (entry.name == 'libsdl') {
return _RepositorySkiaLibSdlDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositorySkiaLibWebPDirectory extends _RepositoryDirectory {
_RepositorySkiaLibWebPDirectory(_RepositoryDirectory super.parent, super.io);
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'webp') {
return _RepositoryReachOutDirectory(this, entry, const <String>{'config.h'}, 3);
}
return super.createSubdirectory(entry);
}
}
class _RepositorySkiaLibSdlDirectory extends _RepositoryDirectory {
_RepositorySkiaLibSdlDirectory(_RepositoryDirectory super.parent, super.io);
@override
bool get isLicenseRootException => true;
}
class _RepositoryBoringSSLDirectory extends _RepositoryDirectory {
_RepositoryBoringSSLDirectory(_RepositoryDirectory super.parent, super.io);
// This directory contains boringssl itself in the 'src' subdirectory,
// and the rest of files are code generated from tools in that directory.
// We redirect any license queries to the src/LICENSE file.
_RepositoryDirectory get src => getChildByName('src') as _RepositoryDirectory;
@override
List<License> nearestLicensesFor(String name) {
final List<License> result = super.nearestLicensesFor(name);
if (result.isEmpty) {
return (src.getChildByName('LICENSE') as _RepositoryLicenseFile).licenses;
}
return result;
}
@override
License? nearestLicenseOfType(LicenseType type) {
assert(!src._canGoUp());
return super.nearestLicenseOfType(type) ?? src.nearestLicenseOfType(type);
}
@override
License? nearestLicenseWithName(String name, {String? authors}) {
assert(!src._canGoUp());
final License? result = super.nearestLicenseWithName(name, authors: authors) ?? src.nearestLicenseWithName(name, authors: authors);
return result;
}
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'src') {
// This is the actual BoringSSL library.
return _RepositoryBoringSSLSourceDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryBoringSSLSourceDirectory extends _RepositoryDirectory {
_RepositoryBoringSSLSourceDirectory(_RepositoryDirectory super.parent, super.io);
// This directory is called "src" because of the way we import boringssl. The
// parent is called "boringssl". Since we are a licenseRoot, the default
// "libraryName" implementation would use "src", so we force it to go up here.
@override
String get libraryName => parent!.libraryName;
@override
bool get isLicenseRoot => true;
}
class _RepositoryFlutterDirectory extends _RepositoryDirectory {
_RepositoryFlutterDirectory(_RepositoryDirectory super.parent, super.io);
@override
String get libraryName => 'engine';
@override
bool get isLicenseRoot => true;
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'third_party') {
return _RepositoryFlutterThirdPartyDirectory(this, entry);
}
return _RepositoryDirectory(this, entry);
}
}
class _RepositoryFlutterThirdPartyDirectory extends _RepositoryGenericThirdPartyDirectory {
_RepositoryFlutterThirdPartyDirectory(super.parent, super.io);
@override
bool shouldRecurse(fs.IoNode entry) {
return entry.name != 'skia' // handled as a virtual directory of the root
&& super.shouldRecurse(entry);
}
@override
_RepositoryDirectory createSubdirectory(fs.Directory entry) {
if (entry.name == 'boringssl') {
return _RepositoryBoringSSLDirectory(this, entry);
}
if (entry.name == 'expat') {
return _RepositoryExpatDirectory(this, entry);
}
if (entry.name == 'freetype2') {
return _RepositoryFreetypeDirectory(this, entry);
}
if (entry.name == 'vulkan-deps') {
return _RepositoryGenericThirdPartyDirectory(this, entry);
}
return super.createSubdirectory(entry);
}
}
class _RepositoryFuchsiaDirectory extends _RepositoryDirectory {
_RepositoryFuchsiaDirectory(_RepositoryDirectory super.parent, super.io);
@override
String get libraryName => 'fuchsia_sdk';
@override
bool get isLicenseRoot => true;
}
class _RepositoryGpuShimDirectory extends _RepositoryDirectory {
_RepositoryGpuShimDirectory(_RepositoryDirectory super.parent, super.io);
@override
String get libraryName => 'engine';
}
/// The license tool directory.
///
/// This is a special-case root node that is not used for license aggregation,
/// but simply to compute a signature for the license tool itself. When this
/// signature changes, we force re-run license collection for all components in
/// order to verify the tool itself still produces the same output.
class _RepositoryFlutterLicenseToolDirectory extends _RepositoryDirectory {
_RepositoryFlutterLicenseToolDirectory(fs.Directory io) : super(null, io);
@override
bool shouldRecurse(fs.IoNode entry) {
return entry.name != 'data' && super.shouldRecurse(entry);
}
}
// BOOTSTRAPPING LOGIC
fs.Directory? findChildDirectory(fs.Directory parent, String name) {
return parent.walk.firstWhereOrNull( // from IterableExtension in package:collection
(fs.IoNode child) => child.name == name,
) as fs.Directory?;
}
class _Progress {
_Progress(this.max, {this.quiet = false}) : millisecondsBetweenUpdates = quiet ? 10000 : 0 {
// This may happen when a git client contains left-over empty component
// directories after DEPS file changes.
if (max <= 0) {
throw ArgumentError('Progress.max must be > 0 but was: $max');
}
}
final int max;
final bool quiet;
final int millisecondsBetweenUpdates;
int get withLicense => _withLicense;
int _withLicense = 0;
int get withoutLicense => _withoutLicense;
int _withoutLicense = 0;
String get label => _label;
String _label = '';
int _lastLength = 0;
set label(String value) {
if (value.length > 60) {
value = '.../${value.substring(math.max(0, value.lastIndexOf('/', value.length - 45) + 1))}';
}
if (_label != value) {
_label = value;
update();
}
}
void advance({required bool success}) {
if (success) {
_withLicense += 1;
} else {
_withoutLicense += 1;
}
update();
}
Stopwatch? _lastUpdate;
void update({bool flush = false}) {
if (_lastUpdate == null || _lastUpdate!.elapsedMilliseconds >= millisecondsBetweenUpdates || flush) {
_lastUpdate ??= Stopwatch();
if (!quiet) {
final String line = toString();
system.stderr.write('\r$line');
if (_lastLength > line.length) {
system.stderr.write(' ' * (_lastLength - line.length));
}
_lastLength = line.length;
}
_lastUpdate!.reset();
_lastUpdate!.start();
}
}
void flush() => update(flush: true);
bool get hadErrors => _withoutLicense > 0;
@override
String toString() {
final int percent = (100.0 * (_withLicense + _withoutLicense) / max).round();
return '${(_withLicense + _withoutLicense).toString().padLeft(10)} of ${max.toString().padRight(6)} '
'${'█' * (percent ~/ 10)}${'░' * (10 - (percent ~/ 10))} $percent% '
'${ _withoutLicense > 0 ? "($_withoutLicense missing licenses) " : ""}'
'$label';
}
}
final RegExp _signaturePattern = RegExp(r'^Signature: (\w+)$', multiLine: true, expectNoMatch: true);
/// Reads the signature from a golden file.
String? _readSignature(String goldenPath) {
try {
final system.File goldenFile = system.File(goldenPath);
if (!goldenFile.existsSync()) {
system.stderr.writeln(' Could not find signature file ($goldenPath).');
return null;
}
final String goldenSignature = goldenFile.readAsStringSync();
final Match? goldenMatch = _signaturePattern.matchAsPrefix(goldenSignature);
if (goldenMatch != null) {
return goldenMatch.group(1);
}
system.stderr.writeln(' Signature file ($goldenPath) did not match expected pattern.');
} on system.FileSystemException {
system.stderr.writeln(' Failed to read signature file ($goldenPath).');
return null;
}
return null;
}
/// Writes a signature to an [system.IOSink] in the expected format.
void _writeSignature(String signature, system.IOSink sink) {
sink.writeln('Signature: $signature\n');
}
// Checks for changes to the license tool itself.
//
// Returns true if changes are detected.
Future<bool> _computeLicenseToolChanges(_RepositoryDirectory root, { required String goldenSignaturePath, required String outputSignaturePath }) async {
final fs.Directory flutterNode = findChildDirectory(root.ioDirectory, 'flutter')!;
final fs.Directory toolsNode = findChildDirectory(flutterNode, 'tools')!;
final fs.Directory licenseNode = findChildDirectory(toolsNode, 'licenses')!;
final _RepositoryDirectory licenseToolDirectory = _RepositoryFlutterLicenseToolDirectory(licenseNode);
final String toolSignature = await licenseToolDirectory.signature;
final system.IOSink sink = system.File(outputSignaturePath).openWrite();
_writeSignature(toolSignature, sink);
await sink.close();
final String? goldenSignature = _readSignature(goldenSignaturePath);
return toolSignature != goldenSignature;
}
/// Collects licenses for the specified component.
///
/// If [writeSignature] is set, the signature is written to the output file.
/// If [force] is set, collection is run regardless of whether or not the signature matches.
Future<void> _collectLicensesForComponent(_RepositoryDirectory componentRoot, {
required String inputGoldenPath,
String? outputGoldenPath,
required bool writeSignature,
required bool force,
required bool quiet,
}) async {
final String signature = await componentRoot.signature;
if (writeSignature) {
// Check whether the golden file matches the signature of the current contents of this directory.
// (We only do this for components where we write the signature, since if there's no signature,
// there's no point trying to read it...)
final String? goldenSignature = _readSignature(inputGoldenPath);
if (!force && goldenSignature == signature) {
system.stderr.writeln(' Skipping this component - no change in signature');
return;
}
}
final _Progress progress = _Progress(componentRoot.fileCount, quiet: quiet);
final system.File outFile = system.File(outputGoldenPath!);
final system.IOSink sink = outFile.openWrite();
if (writeSignature) {
_writeSignature(signature, sink);
}
final List<GroupedLicense> licenses = groupLicenses(componentRoot.assignLicenses(progress));
if (progress.hadErrors) {
throw 'Had failures while collecting licenses.';
}
progress.label = 'Dumping results...';
progress.flush();
final List<String> output = licenses.map((GroupedLicense license) => license.toStringDebug()).toList();
for (int index = 0; index < output.length; index += 1) {
// The strings we look for here are strings which we do not expect to see in
// any of the licenses we use. They either represent examples of misparsing
// licenses (issues we've previously run into and fixed), or licenses we
// know we are trying to avoid (e.g. the GPL, or licenses that only apply to
// test content which shouldn't get built at all).
// If you find that one of these tests is getting hit, and it's not obvious
// to you why the relevant license is a problem, please ask around (e.g. try
// asking Hixie). Do not merely remove one of these checks, sometimes the
// issues involved are relatively subtle.
if (output[index].contains('Version: MPL 1.1/GPL 2.0/LGPL 2.1')) {
throw 'Unexpected trilicense block found in:\n${output[index]}';
}
if (output[index].contains('The contents of this file are subject to the Mozilla Public License Version')) {
throw 'Unexpected MPL block found in:\n${output[index]}';
}
if (output[index].contains('You should have received a copy of the GNU')) {
throw 'Unexpected GPL block found in:\n${output[index]}';
}
if (output[index].contains('Contents of this folder are ported from')) {
throw 'Unexpected block found in:\n${output[index]}';
}
if (output[index].contains('https://github.com/w3c/web-platform-tests/tree/master/selectors-api')) {
throw 'Unexpected W3C content found in:\n${output[index]}';
}
if (output[index].contains('http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html')) {
throw 'Unexpected W3C copyright found in:\n${output[index]}';
}
if (output[index].contains('It is based on commit')) {
throw 'Unexpected content found in:\n${output[index]}';
}
if (output[index].contains('The original code is covered by the dual-licensing approach described in:')) {
throw 'Unexpected old license reference found in:\n${output[index]}';
}
if (output[index].contains('must choose')) {
throw 'Unexpected indecisiveness found in:\n${output[index]}';
}
}
sink.writeln(output.join('\n'));
sink.writeln('Total license count: ${licenses.length}');
await sink.close();
progress.label = 'Done.';
progress.flush();
system.stderr.writeln();
}
// MAIN
Future<void> main(List<String> arguments) async {
final ArgParser parser = ArgParser()
..addOption('src', help: 'The root of the engine source.')
..addOption('out', help: 'The directory where output is written. (Ignored if used with --release.)')
..addOption('golden', help: 'The directory containing golden results.')
..addFlag('quiet', help: 'If set, the diagnostic output is much less verbose.')
..addFlag('verbose', help: 'If set, print additional information to help with development.')
..addFlag('release', help: 'Print output in the format used for product releases.');
final ArgResults argResults = parser.parse(arguments);
final bool quiet = argResults['quiet'] as bool;
final bool verbose = argResults['verbose'] as bool;
final bool releaseMode = argResults['release'] as bool;
if (argResults['src'] == null) {
print('Flutter license script: Must provide --src directory');
print(parser.usage);
system.exit(1);
}
if (!releaseMode) {
if (argResults['out'] == null || argResults['golden'] == null) {
print('Flutter license script: Must provide --out and --golden directories in non-release mode');
print(parser.usage);
system.exit(1);
}
if (!system.FileSystemEntity.isDirectorySync(argResults['golden'] as String)) {
print('Flutter license script: Golden directory does not exist');
print(parser.usage);
system.exit(1);
}
final system.Directory out = system.Directory(argResults['out'] as String);
if (!out.existsSync()) {
out.createSync(recursive: true);
}
}
try {
system.stderr.writeln('Finding files...');
final fs.FileSystemDirectory rootDirectory = fs.FileSystemDirectory.fromPath(argResults['src'] as String);
final _RepositoryDirectory root = _EngineSrcDirectory(rootDirectory);
if (releaseMode) {
system.stderr.writeln('Collecting licenses...');
final _Progress progress = _Progress(root.fileCount, quiet: quiet);
final List<GroupedLicense> licenses = groupLicenses(root.assignLicenses(progress));
if (progress.hadErrors) {
throw 'Had failures while collecting licenses.';
}
progress.label = 'Dumping results...';
progress.flush();
final String output = licenses
.where((GroupedLicense license) => license.body.isNotEmpty)
.map((GroupedLicense license) => license.toStringFormal())
.join('\n${"-" * 80}\n');
print(output);
progress.label = 'Done.';
progress.flush();
system.stderr.writeln();
} else {
// If changes are detected to the license tool itself, force collection
// for all components in order to check we're still generating correct
// output.
const String toolSignatureFilename = 'tool_signature';
final bool forceRunAll = await _computeLicenseToolChanges(
root,
goldenSignaturePath: path.join(argResults['golden'] as String, toolSignatureFilename),
outputSignaturePath: path.join(argResults['out'] as String, toolSignatureFilename),
);
if (forceRunAll) {
system.stderr.writeln('Detected changes to license tool. Forcing license collection for all components.');
}
final List<String> usedGoldens = <String>[];
bool isFirstComponent = true;
for (final _RepositoryDirectory component in root.subdirectories) {
system.stderr.writeln('Collecting licenses for ${component.io.name}');
_RepositoryDirectory componentRoot;
if (isFirstComponent) {
// For the first component, we can use the results of the initial repository crawl.
isFirstComponent = false;
componentRoot = component;
} else {
// For other components, we need a clean repository that does not
// contain any state left over from previous components.
componentRoot = _EngineSrcDirectory(rootDirectory)
.subdirectories
.firstWhere((_RepositoryDirectory dir) => dir.name == component.name);
}
final String goldenFileName = 'licenses_${component.io.name}';
await _collectLicensesForComponent(
componentRoot,
inputGoldenPath: path.join(argResults['golden'] as String, goldenFileName),
outputGoldenPath: path.join(argResults['out'] as String, goldenFileName),
writeSignature: component.io.name != 'flutter',
// Always run the full license check on the flutter tree. The flutter
// tree is relatively small and changes frequently in ways that do not
// affect the license output, and we don't want to require updates to
// the golden signature for those changes.
force: forceRunAll || component.io.name == 'flutter',
quiet: quiet,
);
usedGoldens.add(goldenFileName);
}
final Set<String> unusedGoldens = system.Directory(argResults['golden'] as String).listSync()
.map<String>((system.FileSystemEntity file) => path.basename(file.path))
.where((String name) => name.startsWith('licenses_'))
.toSet()
..removeAll(usedGoldens);
if (unusedGoldens.isNotEmpty) {
system.stderr.writeln('The following golden files in ${argResults['golden']} are unused and need to be deleted:');
unusedGoldens.map((String s) => ' * $s').forEach(system.stderr.writeln);
system.exit(1);
}
// write to disk the list of files we did _not_ cover, so it's easier to catch in diffs
final String excluded = (_RepositoryDirectory._excluded.map(
(fs.IoNode node) => node.fullName,
).toSet().toList()..sort()).join('\n');
system.File(path.join(argResults['out'] as String, 'excluded_files')).writeAsStringSync(
'$excluded\n',
);
}
} catch (e, stack) {
system.stderr.writeln();
system.stderr.writeln('failure: $e\n$stack');
system.stderr.writeln('aborted.');
system.exit(1);
} finally {
if (verbose) {
RegExp.printDiagnostics();
}
}
}
| engine/tools/licenses/lib/main.dart/0 | {
"file_path": "engine/tools/licenses/lib/main.dart",
"repo_id": "engine",
"token_count": 28710
} | 480 |
// Copyright 2013 The Flutter 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 'dart:io' as io;
import 'package:engine_build_configs/engine_build_configs.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:path/path.dart' as p;
// Usage:
// $ dart bin/check.dart [/path/to/engine/src]
void main(List<String> args) {
final String? engineSrcPath;
if (args.isNotEmpty) {
engineSrcPath = args[0];
} else {
engineSrcPath = null;
}
// Find the engine repo.
final Engine engine;
try {
engine = Engine.findWithin(engineSrcPath);
} catch (e) {
io.stderr.writeln(e);
io.exitCode = 1;
return;
}
// Find and parse the engine build configs.
final io.Directory buildConfigsDir = io.Directory(p.join(
engine.flutterDir.path,
'ci',
'builders',
));
final BuildConfigLoader loader = BuildConfigLoader(
buildConfigsDir: buildConfigsDir,
);
// Treat it as an error if no build configs were found. The caller likely
// expected to find some.
final Map<String, BuilderConfig> configs = loader.configs;
if (configs.isEmpty) {
io.stderr.writeln(
'Error: No build configs found under ${buildConfigsDir.path}',
);
io.exitCode = 1;
return;
}
if (loader.errors.isNotEmpty) {
loader.errors.forEach(io.stderr.writeln);
io.exitCode = 1;
}
// Check the parsed build configs for validity.
for (final String name in configs.keys) {
final BuilderConfig buildConfig = configs[name]!;
final List<String> buildConfigErrors = buildConfig.check(name);
if (buildConfigErrors.isNotEmpty) {
io.stderr.writeln('Errors in ${buildConfig.path}:');
io.exitCode = 1;
}
for (final String error in buildConfigErrors) {
io.stderr.writeln(' $error');
io.exitCode = 1;
}
}
// We require all builds within a builder config to be uniquely named.
final Map<String, Set<String>> builderBuildSet = <String, Set<String>>{};
for (final String builderName in configs.keys) {
final BuilderConfig builderConfig = configs[builderName]!;
final Set<String> builds =
builderBuildSet.putIfAbsent(builderName, () => <String>{});
for (final Build build in builderConfig.builds) {
if (builds.contains(build.name)) {
io.stderr.writeln('${build.name} is duplicated in $builderName\n');
io.exitCode = 1;
}
}
}
}
| engine/tools/pkg/engine_build_configs/bin/check.dart/0 | {
"file_path": "engine/tools/pkg/engine_build_configs/bin/check.dart",
"repo_id": "engine",
"token_count": 925
} | 481 |
// Copyright 2013 The Flutter 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 'dart:io' as io;
import 'package:async_helper/async_helper.dart';
import 'package:engine_repo_tools/engine_repo_tools.dart';
import 'package:litetest/litetest.dart';
import 'package:path/path.dart' as p;
void main() {
late io.Directory emptyDir;
void setUp() {
emptyDir = io.Directory.systemTemp.createTempSync('engine_repo_tools.test');
}
void tearDown() {
emptyDir.deleteSync(recursive: true);
}
group('Engine.fromSrcPath', () {
group('should fail when', () {
test('the path does not end in `${p.separator}src`', () {
setUp();
try {
expect(
() => Engine.fromSrcPath(emptyDir.path),
_throwsInvalidEngineException,
);
} finally {
tearDown();
}
});
test('the path does not exist', () {
setUp();
try {
expect(
() => Engine.fromSrcPath(p.join(emptyDir.path, 'src')),
_throwsInvalidEngineException,
);
} finally {
tearDown();
}
});
test('the path does not contain a "flutter" directory', () {
setUp();
try {
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))..createSync();
expect(
() => Engine.fromSrcPath(srcDir.path),
_throwsInvalidEngineException,
);
} finally {
tearDown();
}
});
test('returns an Engine', () {
setUp();
try {
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))..createSync();
io.Directory(p.join(srcDir.path, 'flutter')).createSync();
io.Directory(p.join(srcDir.path, 'out')).createSync();
final Engine engine = Engine.fromSrcPath(srcDir.path);
expect(engine.srcDir.path, srcDir.path);
expect(engine.flutterDir.path, p.join(srcDir.path, 'flutter'));
expect(engine.outDir.path, p.join(srcDir.path, 'out'));
} finally {
tearDown();
}
});
});
});
group('Engine.findWithin', () {
late io.Directory emptyDir;
void setUp() {
emptyDir = io.Directory.systemTemp.createTempSync('engine_repo_tools.test');
}
void tearDown() {
emptyDir.deleteSync(recursive: true);
}
group('should fail when', () {
test('the path does not contain a "src" directory', () {
setUp();
try {
expect(
() => Engine.findWithin(emptyDir.path),
throwsStateError,
);
} finally {
tearDown();
}
});
test('the path contains a "src" directory but it is not an engine root', () {
setUp();
try {
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))..createSync();
expect(
() => Engine.findWithin(srcDir.path),
throwsStateError,
);
} finally {
tearDown();
}
});
test('returns an Engine', () {
setUp();
try {
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))..createSync();
io.Directory(p.join(srcDir.path, 'flutter')).createSync();
io.Directory(p.join(srcDir.path, 'out')).createSync();
final Engine engine = Engine.findWithin(srcDir.path);
expect(engine.srcDir.path, srcDir.path);
expect(engine.flutterDir.path, p.join(srcDir.path, 'flutter'));
expect(engine.outDir.path, p.join(srcDir.path, 'out'));
} finally {
tearDown();
}
});
test('returns an Engine even if a "src" directory exists deeper in the tree', () {
// It's common to have "src" directories, so if we have something like:
// /Users/.../engine/src/foo/bar/src/baz
//
// And we use `Engine.findWithin('/Users/.../engine/src/flutter/bar/src/baz')`,
// we should still find the engine (in this case, the engine root is
// `/Users/.../engine/src`).
setUp();
try {
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))..createSync();
io.Directory(p.join(srcDir.path, 'flutter')).createSync();
io.Directory(p.join(srcDir.path, 'out')).createSync();
final io.Directory nestedSrcDir = io.Directory(p.join(srcDir.path, 'flutter', 'bar', 'src', 'baz'))..createSync(recursive: true);
final Engine engine = Engine.findWithin(nestedSrcDir.path);
expect(engine.srcDir.path, srcDir.path);
expect(engine.flutterDir.path, p.join(srcDir.path, 'flutter'));
expect(engine.outDir.path, p.join(srcDir.path, 'out'));
} finally {
tearDown();
}
});
});
});
test('outputs an empty list of targets', () {
setUp();
try {
// Create a valid engine.
io.Directory(p.join(emptyDir.path, 'src', 'flutter')).createSync(recursive: true);
io.Directory(p.join(emptyDir.path, 'src', 'out')).createSync(recursive: true);
final Engine engine = Engine.fromSrcPath(p.join(emptyDir.path, 'src'));
expect(engine.outputs(), <Output>[]);
expect(engine.latestOutput(), isNull);
} finally {
tearDown();
}
});
test('outputs a list of targets', () {
setUp();
try {
// Create a valid engine.
io.Directory(p.join(emptyDir.path, 'src', 'flutter')).createSync(recursive: true);
io.Directory(p.join(emptyDir.path, 'src', 'out')).createSync(recursive: true);
// Create two targets in out: host_debug and host_debug_unopt_arm64.
io.Directory(p.join(emptyDir.path, 'src', 'out', 'host_debug')).createSync(recursive: true);
io.Directory(p.join(emptyDir.path, 'src', 'out', 'host_debug_unopt_arm64')).createSync(recursive: true);
final Engine engine = Engine.fromSrcPath(p.join(emptyDir.path, 'src'));
final List<String> outputs = engine.outputs().map((Output o) => p.basename(o.path.path)).toList()..sort();
expect(outputs, <String>[
'host_debug',
'host_debug_unopt_arm64',
]);
} finally {
tearDown();
}
});
test('outputs the latest target and compile_commands.json', () {
setUp();
try {
// Create a valid engine.
final io.Directory srcDir = io.Directory(p.join(emptyDir.path, 'src'))
..createSync(recursive: true);
final io.Directory flutterDir = io.Directory(p.join(srcDir.path, 'flutter'))
..createSync(recursive: true);
final io.Directory outDir = io.Directory(p.join(srcDir.path, 'out'))
..createSync(recursive: true);
// Create two targets in out: host_debug and host_debug_unopt_arm64.
final io.Directory hostDebug = io.Directory(p.join(outDir.path, 'host_debug'))
..createSync(recursive: true);
final io.Directory hostDebugUnoptArm64 = io.Directory(
p.join(outDir.path, 'host_debug_unopt_arm64'),
)..createSync(recursive: true);
final Engine engine = TestEngine.withPaths(
srcDir: srcDir,
flutterDir: flutterDir,
outDir: outDir,
outputs: <TestOutput>[
TestOutput(
hostDebug,
lastModified: DateTime.utc(2023, 9, 23, 21, 16),
),
TestOutput(
hostDebugUnoptArm64,
lastModified: DateTime.utc(2023, 9, 23, 22, 16),
),
],
);
final Output? latestOutput = engine.latestOutput();
expect(latestOutput, isNotNull);
expect(p.basename(latestOutput!.path.path), 'host_debug_unopt_arm64');
expect(latestOutput.compileCommandsJson, isNotNull);
} finally {
tearDown();
}
});
}
// This is needed because async_minitest and friends is not a proper testing
// library and is missing a lot of functionality that was exclusively added
// to pkg/test.
void _throwsInvalidEngineException(Object? o) {
_checkThrow<InvalidEngineException>(o, (_){});
}
// Mostly copied from async_minitest.
void _checkThrow<T extends Object>(dynamic v, void Function(dynamic error) onError) {
if (v is Future) {
asyncStart();
v.then((_) {
Expect.fail('Did not throw');
}, onError: (Object e, StackTrace s) {
if (e is! T) {
// ignore: only_throw_errors
throw e;
}
onError(e);
asyncEnd();
});
return;
}
v as void Function();
Expect.throws<T>(v, (T e) {
onError(e);
return true;
});
}
| engine/tools/pkg/engine_repo_tools/test/engine_repo_tools_test.dart/0 | {
"file_path": "engine/tools/pkg/engine_repo_tools/test/engine_repo_tools_test.dart",
"repo_id": "engine",
"token_count": 3795
} | 482 |
# Copyright 2013 The Flutter Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
source_set("procs") {
sources = [
"vulkan_handle.cc",
"vulkan_handle.h",
"vulkan_interface.cc",
"vulkan_interface.h",
"vulkan_proc_table.cc",
"vulkan_proc_table.h",
]
public_configs = [ "//flutter:config" ]
public_deps = [
"//flutter/fml",
"//flutter/third_party/vulkan-deps/vulkan-headers/src:vulkan_headers",
]
}
| engine/vulkan/procs/BUILD.gn/0 | {
"file_path": "engine/vulkan/procs/BUILD.gn",
"repo_id": "engine",
"token_count": 206
} | 483 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vulkan_device.h"
#include <limits>
#include <map>
#include <vector>
#include "flutter/vulkan/procs/vulkan_proc_table.h"
#include "third_party/skia/include/gpu/vk/GrVkBackendContext.h"
#include "vulkan_surface.h"
#include "vulkan_utilities.h"
namespace vulkan {
constexpr auto kVulkanInvalidGraphicsQueueIndex =
std::numeric_limits<uint32_t>::max();
static uint32_t FindGraphicsQueueIndex(
const std::vector<VkQueueFamilyProperties>& properties) {
for (uint32_t i = 0, count = static_cast<uint32_t>(properties.size());
i < count; i++) {
if (properties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) {
return i;
}
}
return kVulkanInvalidGraphicsQueueIndex;
}
VulkanDevice::VulkanDevice(VulkanProcTable& p_vk,
VulkanHandle<VkPhysicalDevice> physical_device,
bool enable_validation_layers)
: vk_(p_vk),
physical_device_(std::move(physical_device)),
graphics_queue_index_(std::numeric_limits<uint32_t>::max()),
valid_(false) {
if (!physical_device_ || !vk_.AreInstanceProcsSetup()) {
return;
}
graphics_queue_index_ = FindGraphicsQueueIndex(GetQueueFamilyProperties());
if (graphics_queue_index_ == kVulkanInvalidGraphicsQueueIndex) {
FML_DLOG(INFO) << "Could not find the graphics queue index.";
return;
}
const float priorities[1] = {1.0f};
const VkDeviceQueueCreateInfo queue_create = {
.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.queueFamilyIndex = graphics_queue_index_,
.queueCount = 1,
.pQueuePriorities = priorities,
};
const char* extensions[] = {
#if FML_OS_ANDROID
VK_KHR_SWAPCHAIN_EXTENSION_NAME,
#endif
#if OS_FUCHSIA
VK_KHR_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_KHR_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME,
VK_FUCHSIA_EXTERNAL_MEMORY_EXTENSION_NAME,
VK_FUCHSIA_EXTERNAL_SEMAPHORE_EXTENSION_NAME,
VK_FUCHSIA_BUFFER_COLLECTION_EXTENSION_NAME,
#endif
};
auto enabled_layers =
DeviceLayersToEnable(vk_, physical_device_, enable_validation_layers);
std::vector<const char*> layers;
for (size_t i = 0; i < enabled_layers.size(); i++) {
layers.push_back(enabled_layers[i].c_str());
}
const VkDeviceCreateInfo create_info = {
.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.queueCreateInfoCount = 1,
.pQueueCreateInfos = &queue_create,
.enabledLayerCount = static_cast<uint32_t>(layers.size()),
.ppEnabledLayerNames = layers.data(),
.enabledExtensionCount = sizeof(extensions) / sizeof(const char*),
.ppEnabledExtensionNames = extensions,
.pEnabledFeatures = nullptr,
};
VkDevice device = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vk_.CreateDevice(physical_device_, &create_info,
nullptr, &device)) != VK_SUCCESS) {
FML_DLOG(INFO) << "Could not create device.";
return;
}
device_ = VulkanHandle<VkDevice>{
device, [this](VkDevice device) { vk_.DestroyDevice(device, nullptr); }};
if (!vk_.SetupDeviceProcAddresses(device_)) {
FML_DLOG(INFO) << "Could not set up device proc addresses.";
return;
}
VkQueue queue = VK_NULL_HANDLE;
vk_.GetDeviceQueue(device_, graphics_queue_index_, 0, &queue);
if (queue == VK_NULL_HANDLE) {
FML_DLOG(INFO) << "Could not get the device queue handle.";
return;
}
queue_ = VulkanHandle<VkQueue>(queue);
if (!InitializeCommandPool()) {
return;
}
valid_ = true;
}
VulkanDevice::VulkanDevice(VulkanProcTable& p_vk,
VulkanHandle<VkPhysicalDevice> physical_device,
VulkanHandle<VkDevice> device,
uint32_t queue_family_index,
VulkanHandle<VkQueue> queue)
: vk_(p_vk),
physical_device_(std::move(physical_device)),
device_(std::move(device)),
queue_(std::move(queue)),
graphics_queue_index_(queue_family_index),
valid_(false) {
if (!physical_device_ || !vk_.AreInstanceProcsSetup()) {
return;
}
if (!InitializeCommandPool()) {
return;
}
valid_ = true;
}
bool VulkanDevice::InitializeCommandPool() {
const VkCommandPoolCreateInfo command_pool_create_info = {
.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
.pNext = nullptr,
.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT,
.queueFamilyIndex = 0,
};
VkCommandPool command_pool = VK_NULL_HANDLE;
if (VK_CALL_LOG_ERROR(vk_.CreateCommandPool(
device_, &command_pool_create_info, nullptr, &command_pool)) !=
VK_SUCCESS) {
FML_DLOG(INFO) << "Could not create the command pool.";
return false;
}
command_pool_ = VulkanHandle<VkCommandPool>{
command_pool, [this](VkCommandPool pool) {
vk_.DestroyCommandPool(device_, pool, nullptr);
}};
return true;
}
VulkanDevice::~VulkanDevice() {
FML_ALLOW_UNUSED_LOCAL(WaitIdle());
}
bool VulkanDevice::IsValid() const {
return valid_;
}
bool VulkanDevice::WaitIdle() const {
return VK_CALL_LOG_ERROR(vk_.DeviceWaitIdle(device_)) == VK_SUCCESS;
}
const VulkanHandle<VkDevice>& VulkanDevice::GetHandle() const {
return device_;
}
void VulkanDevice::ReleaseDeviceOwnership() {
device_.ReleaseOwnership();
}
const VulkanHandle<VkPhysicalDevice>& VulkanDevice::GetPhysicalDeviceHandle()
const {
return physical_device_;
}
const VulkanHandle<VkQueue>& VulkanDevice::GetQueueHandle() const {
return queue_;
}
const VulkanHandle<VkCommandPool>& VulkanDevice::GetCommandPool() const {
return command_pool_;
}
uint32_t VulkanDevice::GetGraphicsQueueIndex() const {
return graphics_queue_index_;
}
bool VulkanDevice::GetSurfaceCapabilities(
const VulkanSurface& surface,
VkSurfaceCapabilitiesKHR* capabilities) const {
#if FML_OS_ANDROID
if (!surface.IsValid() || capabilities == nullptr) {
return false;
}
bool success =
VK_CALL_LOG_ERROR(vk_.GetPhysicalDeviceSurfaceCapabilitiesKHR(
physical_device_, surface.Handle(), capabilities)) == VK_SUCCESS;
if (!success) {
return false;
}
// Check if the physical device surface capabilities are valid. If so, there
// is nothing more to do.
if (capabilities->currentExtent.width != 0xFFFFFFFF &&
capabilities->currentExtent.height != 0xFFFFFFFF) {
return true;
}
// Ask the native surface for its size as a fallback.
SkISize size = surface.GetSize();
if (size.width() == 0 || size.height() == 0) {
return false;
}
capabilities->currentExtent.width = size.width();
capabilities->currentExtent.height = size.height();
return true;
#else
return false;
#endif
}
bool VulkanDevice::GetPhysicalDeviceFeatures(
VkPhysicalDeviceFeatures* features) const {
if (features == nullptr || !physical_device_) {
return false;
}
vk_.GetPhysicalDeviceFeatures(physical_device_, features);
return true;
}
bool VulkanDevice::GetPhysicalDeviceFeaturesSkia(uint32_t* sk_features) const {
if (sk_features == nullptr) {
return false;
}
VkPhysicalDeviceFeatures features;
if (!GetPhysicalDeviceFeatures(&features)) {
return false;
}
uint32_t flags = 0;
if (features.geometryShader) {
flags |= kGeometryShader_GrVkFeatureFlag;
}
if (features.dualSrcBlend) {
flags |= kDualSrcBlend_GrVkFeatureFlag;
}
if (features.sampleRateShading) {
flags |= kSampleRateShading_GrVkFeatureFlag;
}
*sk_features = flags;
return true;
}
std::vector<VkQueueFamilyProperties> VulkanDevice::GetQueueFamilyProperties()
const {
uint32_t count = 0;
vk_.GetPhysicalDeviceQueueFamilyProperties(physical_device_, &count, nullptr);
std::vector<VkQueueFamilyProperties> properties;
properties.resize(count, {});
vk_.GetPhysicalDeviceQueueFamilyProperties(physical_device_, &count,
properties.data());
return properties;
}
int VulkanDevice::ChooseSurfaceFormat(
const VulkanSurface& surface,
const std::vector<VkFormat>& desired_formats,
VkSurfaceFormatKHR* format) const {
#if FML_OS_ANDROID
if (!surface.IsValid() || format == nullptr) {
return -1;
}
uint32_t format_count = 0;
if (VK_CALL_LOG_ERROR(vk_.GetPhysicalDeviceSurfaceFormatsKHR(
physical_device_, surface.Handle(), &format_count, nullptr)) !=
VK_SUCCESS) {
return -1;
}
if (format_count == 0) {
return -1;
}
std::vector<VkSurfaceFormatKHR> formats;
formats.resize(format_count);
if (VK_CALL_LOG_ERROR(vk_.GetPhysicalDeviceSurfaceFormatsKHR(
physical_device_, surface.Handle(), &format_count, formats.data())) !=
VK_SUCCESS) {
return -1;
}
std::map<VkFormat, VkSurfaceFormatKHR> supported_formats;
for (uint32_t i = 0; i < format_count; i++) {
supported_formats[formats[i].format] = formats[i];
}
// Try to find the first supported format in the list of desired formats.
for (size_t i = 0; i < desired_formats.size(); ++i) {
auto found = supported_formats.find(desired_formats[i]);
if (found != supported_formats.end()) {
*format = found->second;
return static_cast<int>(i);
}
}
#endif
return -1;
}
bool VulkanDevice::ChoosePresentMode(const VulkanSurface& surface,
VkPresentModeKHR* present_mode) const {
if (!surface.IsValid() || present_mode == nullptr) {
return false;
}
// https://github.com/LunarG/VulkanSamples/issues/98 indicates that
// VK_PRESENT_MODE_FIFO_KHR is preferable on mobile platforms. The problems
// mentioned in the ticket w.r.t the application being faster that the refresh
// rate of the screen should not be faced by any Flutter platforms as they are
// powered by Vsync pulses instead of depending the submit to block.
// However, for platforms that don't have VSync providers set up, it is better
// to fall back to FIFO. For platforms that do have VSync providers, there
// should be little difference. In case there is a need for a mode other than
// FIFO, availability checks must be performed here before returning the
// result. FIFO is always present.
*present_mode = VK_PRESENT_MODE_FIFO_KHR;
return true;
}
bool VulkanDevice::QueueSubmit(
std::vector<VkPipelineStageFlags> wait_dest_pipeline_stages,
const std::vector<VkSemaphore>& wait_semaphores,
const std::vector<VkSemaphore>& signal_semaphores,
const std::vector<VkCommandBuffer>& command_buffers,
const VulkanHandle<VkFence>& fence) const {
if (wait_semaphores.size() != wait_dest_pipeline_stages.size()) {
return false;
}
const VkSubmitInfo submit_info = {
.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,
.pNext = nullptr,
.waitSemaphoreCount = static_cast<uint32_t>(wait_semaphores.size()),
.pWaitSemaphores = wait_semaphores.data(),
.pWaitDstStageMask = wait_dest_pipeline_stages.data(),
.commandBufferCount = static_cast<uint32_t>(command_buffers.size()),
.pCommandBuffers = command_buffers.data(),
.signalSemaphoreCount = static_cast<uint32_t>(signal_semaphores.size()),
.pSignalSemaphores = signal_semaphores.data(),
};
if (VK_CALL_LOG_ERROR(vk_.QueueSubmit(queue_, 1, &submit_info, fence)) !=
VK_SUCCESS) {
return false;
}
return true;
}
} // namespace vulkan
| engine/vulkan/vulkan_device.cc/0 | {
"file_path": "engine/vulkan/vulkan_device.cc",
"repo_id": "engine",
"token_count": 4507
} | 484 |
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "vulkan_swapchain.h"
namespace vulkan {
VulkanSwapchain::VulkanSwapchain(const VulkanProcTable& p_vk,
const VulkanDevice& device,
const VulkanSurface& surface,
GrDirectContext* skia_context,
std::unique_ptr<VulkanSwapchain> old_swapchain,
uint32_t queue_family_index) {}
VulkanSwapchain::~VulkanSwapchain() = default;
bool VulkanSwapchain::IsValid() const {
return false;
}
VulkanSwapchain::AcquireResult VulkanSwapchain::AcquireSurface() {
return {AcquireStatus::ErrorSurfaceLost, nullptr};
}
bool VulkanSwapchain::Submit() {
return false;
}
SkISize VulkanSwapchain::GetSize() const {
return SkISize::Make(0, 0);
}
} // namespace vulkan
| engine/vulkan/vulkan_swapchain_stub.cc/0 | {
"file_path": "engine/vulkan/vulkan_swapchain_stub.cc",
"repo_id": "engine",
"token_count": 437
} | 485 |
<?xml version="1.0" encoding="UTF-8"?>
<module version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/tool/plugin/build" />
<excludeFolder url="file://$MODULE_DIR$/.pub" />
<excludeFolder url="file://$MODULE_DIR$/tool/plugin/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/tool/plugin/.pub" />
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
<excludeFolder url="file://$MODULE_DIR$/build" />
</content>
</component>
</module> | flutter-intellij/.idea/flutter-intellij.iml/0 | {
"file_path": "flutter-intellij/.idea/flutter-intellij.iml",
"repo_id": "flutter-intellij",
"token_count": 228
} | 486 |
# 66.0
- Use expandable test field for run args (#6065)
- Ignore scratch files during hot reload on save (#6064)
- Stop using some deprecated methods (#5994)
- Allow directories to be recognized as part of a Flutter project (#6057)
- Drop 2020.3, update Dart plugin for latest EAP (#6059)
- Check for bazel workspace when using VM mapping (#6055)
- Add jxbrowser log file for easier debugging (#6051)
- Notify bazel users to try running iOS apps (#6028)
- Use VM service for mapping breakpoint URIs (#6044)
- Send internal errors to analytics for disconnections (#6005)
# 65.0
- Change .packages file use to package config file (#5993)
- Add Android module when opening any project (#5991)
- Update JxBrowser to 7.22 (#5990)
- Use time zone in survey calculation (#5976)
- Fix return type of createState in macros (#5963)
- Log perf dispose NPEs (#5975)
- Build for 2022.1 EAP (#5973)
- Remove old bazel test file mapping code (#5974)
- Use VM for mapping breakpoint files during app run (#5947)
- Update for 64.1 (#5958)
- Try SIGINT first for all processes (#5950)
- Open AS 2021.x (#5951)
- Build for canary (Dolphin) (#5937)
# 64.1
- Try SIGINT before SIGKILL for processes (#5950)
# 64.0
- Fix modules for working with AS sources (#5913)
- Add analytics to survey notifications (#5912)
- Update AS modules for 212 (#5905)
- Build for 212.5712 (#5894)
- Improve icon preview and completion performance (#5887)
- Rename old load classes (#5884)
- Use IJ 213 for unit tests (#5882)
- Share resources with both modules (#5877)
# 63.0
- Build for IntelliJ 2021.3 and Android Studio canary (#5868)
- Enable downloading Mac M1 version of JxBrowser (#5871)
- Convert to Gradle project with Kotlin DSL (#5858)
# 62.0
- Update jxbrowser to 7.19 (#5783)
- Restore ignored tests (#5826)
- Use Java 11 everywhere (#5836)
- Add AS Canary to dev channel (#5830)
- Remove dependencies on built-in Flutter icons (#5824)
- Add instructions for converting to/from Gradle project (#5822)
- Derive icon previews from font files for built-in icons (#5820)
- Enable more compile-time nulllability checking (#5804)
# 61.1
- Add null check for manager (#5799)
# 61.0
- Make console stack traces expandable (#5777)
- Do hot reload on auto-save (#5774)
- Run flutter pub get after changing SDK in preferences (#5773)
- Allow tests in any marked test dir and optionally in sources (#5770)
- Add the new skeleton template to the New Project Wizard (#5765)
- Bug fix in Workspace.java: parsing of contents out of the json file. (#5768)
- Make unit test name matching more strict (#5763)
- Stop running an external tool before launching (#5759)
- Change some deprecated API usage (#5755)
- Try harder to find pub root (#5753)
- Add --project-name arg to flutter create (#5752)
- Delete the project directory if project validation fails (#5751)
- Build menu should be visible even if no file is selected (#5750)
- Fix broken image resorce link (#5745)
- Convert back to iml-based project (#5741)
- Remove old code from NPW (#5739)
- Fix some problems in the set up docs (#5734)
# 60.1
- Add project type selection to new project wizard for Android Studio
# 60.0
- Modify run configs to ensure proper artifacts have been provisioned (#5729)
- Update test setup instructions (#5728)
- Ignore errors reported when Android Studio is launched (#5726)
- Convert repo to a Gradle-based project (#5720)
- Delete two obsolete tests and attempt to de-flake others (#5715)
- Port over support for special list display in the debugger (#5713)
- Update build script for AS canary (#5709)
- Refactor icon preview processing to be incremental (#5704)
- Add "mdof" live template for MediaQuery.of(context) (#5698)
# 59.0
- Update installation instructions for Windows
- Make reanalyze() work after packages are removed from icon package list (#5678)
- Optimize icon preview processing for multiple analyses (#5677)
- Handle the new event format for widget recount info (#5671)
- Update to jxbrowser 7.17 (#5675)
- Remove creating flutter_build_mode flag (#5654)
- Remove custom listeners before a project is closed
- Persist tool window open states during project open/close (#5664)
- Use off screen render mode for linux (#5663)
- Add analytics for null analyzer during add breakpoint (#5626)
- Add menu item to Open in AppCode (#5660)
- Disallow iOS builds if not on Mac (#5657)
- Add a field for environment variables to the run config editor (#5656)
- Add mockito to build.gradle (#5645)
- Remove powermock from FlutterView tests and remove non-stack uses (#5644)
- Update docs for yaml plugin (#5642)
- Add mockito library (#5641)
- Stop asking to delete coverage data (#5640)
- Dynamic icon preview of non-standard icon packages (#5595)
- Detect repeated daemon crashes and provide recovery hint (#5638)
- Update live templates to not use double underscores (#5619)
- Fix Android Studio path on Linux (#5605)
- Open source file in Android Studio at exact cursor (#5606)
- Check for project disposal right before organize executes (#5624)
- Skip Flutter tool windows for non-Flutter projects (WIP) (#5622)
- Add force scale option for linux (#5618)
# 58.0
- Add some NotNull annotations in the FlutterWidgetPerf classes; rev to the latest VM service protocol lib (#5588)
- Check for disposed project before getting embedded browser (#5590)
- Allow open DevTools from tests (#5279)
- Add field for Dart entrypoint in bazel configuration form (#5155)
- Check for initial open state of embedded browser (#5580)
- Send caught exceptions as events (#5576)
- Fix custom component in a presentation update issue (#5577)
- Update build for AS canary (#5575)
- Update jxbrowser to v7.16 (#5574)
- Update the Inspector to prep for changes to the widget transformer (#5570)
- Adapt to breaking API change in 212 (#5567)
- Use 2021.2 for unit tests (#5565)
- Change embedded browser setting (#5561)
- Fix an index out of bounds in FlutterSdk.java (#5559)
- Allow Instance fields to be nullable (#5554)
- Fix a bunch of test failures on Windows (#5553)
- Add a section on configuring a Windows dev env (#5545)
- Display test coverage in the editor (#5544)
- Generate icons from a font file (#5504)
- Add switch to disable notifications (#5539)
- Clean up unused version for bazel (#5535)
- Switch the repo's analysis options to using package:lints (#5534)
- Stop using DevTools URL util method, reorg tests (#5517)
- Update the set of supported IntelliJ versions (#5520)
# 57.0
- Update to JxBrowser v7.15 (#5511)
- Catch InvalidVirtualFileAccessException thrown by VFS in a readAction (#5510)
- Handle if embedded browser load fails (#5509)
- Add null-check for listener (#5508)
- Enable embedded browser (once) for Big Sur users (#5490)
- Update live templates to assume null-safety (#5494)
- Detect M1 mac and skip JxBrowser (#5487)
- Use --config-only to set up Xcode (#5489)
- Fix jump-to-source for testWidgets() (#5486)
- Use i18n version of "Console" (#5483)
- Fix step-over async call (#5476)
- Update device selector on EDT (#5480)
- Catch an already disposed exception (#5479)
- Make sure presentDevTools runs on event thread (#5471)
- Fix NPE when no integration test folder exists (#5473)
- Run tests with coverage (#5463)
- Add support for integration tests to the UI (#5459)
- Check for new local Dart SDK (#5456)
- Improve hover message of "Track Widget Rebuilds" (#5451)
# 56.0
- Add option to display all stack traces in debugger log (#5443)
- Cleanup and refactoring in editor notification providers (#5425)
- Allow IconData(null) (#5440)
- Report VM service connection problems (#5426)
- Add more proper configuration step in the contributing doc (#5438)
- Update to JxBrowser 7.14 (#5434)
- Log JxBrowser exceptions as info (#5432)
- Add constructor in widget live templates (#5405)
- Update change log for 55.1 (#5413)
- Check for NoClassDefFoundError before setting JxBrowser enabled (#5402)
- Add the ability of the Flutter plugin to check for the installation of an IJ plugin as specified by the Bazel workspace (#5401)
- Listen for theme color changes to update embedded browser (#5372)
- Fix null-safety error (#5371)
- Follow up on the isFailure json attribute change, removal of the error attribute to match the Dart IJ Plugin (#5369)
- Remove the isFailure option in the Dart test event framework (#5345)
# 55.1
- Check for NoClassDefFoundError before setting JxBrowser enabled (#5402)
# 55.0
- Disable bazel hot restart by default (#5349)
- Change action group name for canary (#5362)
- Handle include lists in settings.gradle (#5353)
- Fix typo in CONTRIBUTING.md (#5344)
- Add a parameter to Project.initProject() for canary (#5346)
- Report DevTools timeout but remove from console log (#5343)
- Skip URL reset if JxBrowser not installed (#5341)
- Use proper package file (#5340)
- Disable Android framework detection for Flutter projects (#5336)
- Refresh devices (#5333)
- Check that files exist during class load (#5334)
- Catch class loading exceptions and log full path (#5332)
- Fix the lost SDK on start up problem (#5325)
- Update dev install instructions (#5330)
- Log any exceptions on jxbrowser close and check closed status (#5303)
- Register highlighting for Flutter projects only (#5300)
- Get device list after indexing finishes (#5296)
- Update to JxBrowser v7.13 and remove Big Sur checks (#5295)
# 54.1
- Support 2021.1 Beta
- Simplify platform selection code (#5314)
# 54.0
- Fix platform selector bug (#5280)
- Permit deep link to open embedded browser (#5277)
- Add attach args field to run config (#5276)
- Build using 2020.2 platform SDK (#5270)
- Stop adding --platforms for packages (#5273)
- Add analytics for deep link clicked (#5269)
- Run flutter channel if git is not available (#5268)
- Fix unit tests (#5267)
- Add a type check (#5266)
- Restore stand-alone project file (#5265)
- Skip waiting for DevTools after first run (#5263)
- Check for content manager disposed before replacing panel (#5261)
- Delay loading embedded browser until inspector visible (#5256)
- Compare master versions with beta (#5254)
- XCode -> Xcode casing (#5251)
- Fix build for AS canary 5 (#5250)
- Expire deep link notification on click (#5239)
- Modify password store to avoid keyring prompts (#5226)
- Add version null check for DevTools URL support (#5227)
# 53.0
- Restart DevTools and browser on inspector window reopen (#5218)
- Show notification on error with deep link (#5207)
- Refresh the channel cache when the SDK changes (#5208)
- Update jxbrowser version and set DPI property (#5205)
- Show icons only for known sets (#5201)
- Handle time-out when getting Flutter SDK (#5191)
- Add run icon to definition of main() (#5199)
- Pass DevTools server URL to bazel run also (#5197)
- Start DevTools server and pass address to run (#5176)
- Add a null check before dereferencing sourcePosition (#5194)
- Add compare function that works for beta versions (#5192)
- Add null checks to debugActive() (#5190)
- Show "Lost connection to device." in red (#5189)
- Remove newlines prior to sending eval expr to VM (#5187)
- Log console messages from embedded browser (#5180)
- Fix args parsing in launch configurations (#5181)
- Update color and icon previews (#5177)
- Update JxBrowser contributing instructions (#5175)
- Rename to "Flutter DevTools" (#5173)
- Show custom dialog for embedded browser (#5163)
- Add link to install docs to NPW (#5161)
- Use ColoredProcessHandler for the console (#5151)
- Add JxBrowser logs when verbose enabled (#5156)
- Track time lapsed to start analysis server and finish indexing (#5153)
- Close embedded browser engine on application close (#5142)
- Use DevTools service in performance action and delete manager (#5144)
- Send exception if DevTools server fails to start (#5148)
- Use project-level DevTools server for overflow open (#5143)
- Use DevTools service for open action (#5141)
- Remove launch script and devtools script (#5087)
- Sync before hot reload for bazel projects (#5114)
- Remove install SDK button from NPW (#5131)
- Some minor cleanups to the dart code (#5136)
- Update the contributing docs (#5135)
- Start DevTools server on first request and handle exceptions (#5130)
- Add platforms to the new project wizard (#5070)
- Add callback for if jxbrowser fails (#5129)
- Minor tweaks to the snap sdk path code (#5124)
- Update tool docs (#5126)
- Use project DevTools server for embedded browser (#5121)
- Add Flutter snap path to getKnownFlutterSdkPaths() (#5123)
- Open DevTools directly using pub for external projects (#5116)
- Add devtools service (#5112)
- Run devtools panel actions on UI thread (#5085)
- Update the live templates (#5101)
- Slight change to github actions (#5105)
- Revert to 2020.2.4 to run unit tests (#5097)
- Save instance of devtools between bazel app runs (#5096)
- Stop devtools process on closing (#5094)
- Use existing devtools for bazel in panel and remove opening devtools for tests (#5066)
- Fix json parsing (#5081)
- Add dispatch events to run actions (#5068)
# 52.2
- Fix an issue with leaking subscriptions (#5115)
- Fix an error caused by an API change in AS canary 4 (#5165)
# 52.1
- Add additional args field to test config (#5122)
# 52.0
- Move launching of Android Studio off EDT onto a background thread #5081
- Unset and disable embedded browser option if MacOS Big Sur (#5065)
- Send SIGINT for bazel test processes (#5064)
- Update to jxbrowser v7.12 (#5060)
- Use OFF_SCREEN render mode for windows (#5055)
- Channel command: run 'flutter channel' (#5048)
- Use runScript for bazel run (#5046)
- Add instructions to run tests on command line (#5047)
- Minor NPW clean up (#5045)
- Simplify the new project wizard for AS 4.2+ (#5044)
- Set user-data folder for embedded browser (#5035)
- Fix copy/paste error in change log (#5021)
- Mock inspector group manager to fix test (#5017)
# 51.0
- Fix bugs where widget indent behavior sometimes impacted non-dart files, stale indent guides were sometimes displayed, and filtered indent guides were unpredictably displayed (#5008)
- Allow bazel projects to set up JxBrowser (#5007)
- Make embedded browser default enabled, not version-specific (#5006)
- Change predicate type for EAP (#5002)
- Remove deprecated command (#4995)
- Require a project parameter when creating notifications (#4972)
- Remove all androidx references (#4993)
- Fix hang when opening a project if previous selection was a directory (#4991)
- Minor tweaks to an error message (#4976)
- Enable embedded browser by default (#4988)
- Improved aesthetics for the run console folding (#4975)
- Fix an issue with unnamed test groups (#4980)
- Migrate to IntelliJ NPW for AS 4.3 (#4985)
- Resume isolates at test start (#4977)
- Show option to open DevTools in browser during JxBrowser installation (#4983)
- Record whether the project type is bazel (#4971)
- Fix a deprecation warning (#4970)
- Show option to open browser DevTools on general download failure (#4969)
- Fix an issue with displaying flutter errors in terse mode (#4966)
- Add analytics for download finished (#4963)
- Add more detail for JxBrowser failed downloads (#4948)
- Adjust the layout for the jxbrowser error feedback ui (#4945)
- Prevent repeat downloads of JxBrowser files (#4949)
- Address an issue with the JsBrowser singleton (#4944)
- Stop downloading ant on kokoro (#4947)
- Fix a null assertion in the inspector (#4938)
- Fix an exception loading the FlutterIconProvider class in EAP (#4942)
- Update the DartElementPresentationUtil class (#4915)
- Update the FlutterSearchableOptionContributor class (#4935)
- Various lint fixes (#4931)
- Collect analytics for the 'enable hot ui' setting (#4910)
- Address various lints in src/io/flutter/perf, src/io/flutter/performance, src/io/flutter/module (#4918)
- Resize the flutter outline view icons to be slightly smaller (#4916)
- Send the flutter sdk version with the analytics for flutter errors (#4913)
- Re-add widgets.json (#4919)
- Remove the widget catalog file and related code (#4917)
- Make the settings page more compact (#4900)
- Remove an older wizard for small IDEs (#4908)
- Make the device param into various run methods not null (#4903)
- Change FileUtils to instance for easier mocking (#4909)
- Adjust the text for the jxbrowser setting (#4907)
- Make the flutter settings page slightly more compact (#4899)
- Remove the explicit disable track widget creation option (#4902)
# 50.0
- More general lint cleanups (#4865)
- Improve the flutter error ids we generate for analytics (#4870)
- Update flutter framework metadata (#4866)
- Move off two deprecated APIs (#4864)
- Only send analytics for the first error for a frame (#4867)
- More lint cleanups (#4861)
- Address lints on JxBrowserManager.java (#4858)
- Open DevTools in standard browser if JxBrowser license is missing (#4823)
- Remove FlutterLogView and associated classes (#4857)
- Move DartTestLocationProviderZ to io.flutter.run.test (#4851)
- Update our project linting rules and fix various lints (#4845)
- Support pausing a running app (#4847)
- Redirect json parsing calls to JsonUtils (#4846)
- Move off some deprecated methods (#4843)
- Remove a log error about no isolates (#4842)
- Various misc. fixes (#4840)
- Remove 2019.2 from the product matrix (#4838)
- Fix an NPE from console logging (#4834)
- Fix an issue parsing color values (#4836)
- Only reference runtime artifacts for testing (#4829)
- Update to the latest VM service protocol library (#4828)
- Log exception when JxBrowser license key file is missing (#4821)
- Remove extra page param for launching DevTools (#4802)
- Skip transparent background if hardware accelerated causes error (#4804)
- Fix an issue with the JsonParser.parseString() API (#4816)
- Add JxBrowser installation events (#4791)
- Upgrade the vm service protocol library (#4813)
# 49.0
- Use PluginManager method for Android Studio and move function (#4794)
- Enable embedded browser by default in dev (#4790)
- Update flutter resources (#4789)
- Send IntelliJ component background color to devtools (#4788)
- Fix white screen during embedded browser load (#4787)
- Add note on LGPL compliance to plugin description (#4786)
- Add experimental setting for embedding devtools (#4785)
- Don't cache VirtualFiles for '.packages' file and 'lib' folder. (#4781)
- Load correct file path for JxBrowser files (#4782)
- Skip write for empty JxBrowser key (#4783)
- Use JxBrowser key during build process (#4773)
- FlutterDependencyInspection shouldn't work in a non-Flutter project (#4780)
- Add tests for JxBrowserManager logic and add test comments (#4714)
- Use JxBrowser version 7.10 (#4769)
- Use daemon API to get devtools host and port for internal use (#4733)
- Skip start-paused for web server in run mode (#4766)
- Show run console and skip breakpoints during test run (#4749)
# 48.1
- Avoid start-paused for directory scope tests (#4748)
- Fix Android Studio canary build (#4745)
- Fix CHANGELOG version headings (#4739)
# 48.0
- Show notification for when devtools build is slow (#4728)
- Use the new, generated metadata from flutter/tools_metadata (#4724)
- Remove the framework metadata generation code from this repo (#4721)
- Suppress several UnstableApiUsage warnings (#4722)
- Update terminology to Allow List (#4723)
- Resolve the issue displaying color icons in IntelliJ Idea and Android studio [ISSUE-3347] (#4695)
- Add handling and messaging for when JxBrowser is not installed (#4712)
- Update our analytics text (#4711)
- Add JxBrowser dependencies and show in panel (#4664)
- Start paused for run mode and use FlutterTestRunner for run tests (#4678)
- Update the device selector presentation on toolbar change (#4698)
- Stop checking for BUILD when looking for root dir (#4693)
- Build issues (#4688)
- Flutter news (#4680)
- Simplify regex and sort colors (#4687)
- Split icon generation into two scripts + use single set of downloaded files (#4671)
- Update build script (#4674)
# 47.1
- Revert "Start paused during run mode (#4622)" (#4673)
- Add target to registerComponents() (#4672)
# 47.0
- Adapt to API changes in AS 4.2c2 (#4652)
- Fix a display issue with the device selector (#4651)
- Update product matrix for canary (#4645)
- Dual regex (#4634)
- Update the InheritedWidget template (#4636)
- Recognize \r as newlines from flutter (#4633)
- Update tool/colors to support generating mapping for CupertinoColor (#4628)
- Start paused during run mode (#4622)
- Avoid updating subscribers if bazel project is disconnected (#4603)
- Stop specifying project name during creation (#4615)
- Update integration tests for canary (#4612)
- Update build to support canary (#4604)
- Use lazy regexp with bounds (#4605)
- Display structured errors immediately (#4587)
- Upgrade ant for kokoro (#4594)
- Remove a delay with hot reload (#4595)
# 46.0
- Apply link filter to error messages
- Save files before launching debug tests (#4556)
- Add null check to device refresh (#4557)
- Add device selector refresh button for internal projects (#4550)
- Allow internal Dart SDK paths (#4546)
- Prevent drawing child lines through other chars (#4522)
- Update tests for 2020.1 (#4530)
- Update setup instructions (#4520)
- Update the material and cupertino icons (#4517)
- In-line run config names to address runtime wanrings (#4500)
- Only show the Flutter device selector in projects that have a Flutter module (#4483)
# 45.1
- Automatically re-import add-to-app module when host app is opened for the first time (#4479)
- Harden survey checking network access (#4469)
- Restore missing Attach Debugger action (#4468)
# 45.0
- Add support for 'flutter pub outdated' (#4444)
- Improve how we calculate when to summarize flutter errors (#4447)
- Fix an issue with discovering hyperlinks in test consoles (#4443)
- Delete unused redundant test (#4438)
- Fix an NPE in CommonTestConfigUtils.java (#4437)
- Revive GUI test NewProjectTest (#4434)
- Fix link to Flutter docs (#4435)
- Revive the GUI test NewModuleTest (#4432)
- Build for AS 4.1; start fixing integration tests (#4428)
- Fix API incompatibilities (#4423)
- Remove an unused flutter command (#4415)
- No longer depend on JBRunnerTabs implementing Disposable (#4406)
- Ensure indexing is finished before updating library model (#4409)
# 44.0
- Use --project-name in flutter create (#4389)
- Check for disposed project (#4391)
- Replace deprecated API usage (#4390)
- Switch common test config utils to use a per-file cache (#4385)
- Make the gitignore more specific for content within the .idea directory (#4380)
- Print the debug service uri on app startup (#4381)
- Fix crash caused by getting flutter view id with .join() (#4373)
- Change flutter.io to flutter.dev (#4376)
- Update README.md (#4374)
- Tidy up old domain name links (#4370)
- Remove use of deprecated APIs (#4351)
- Push back survey window (#4348)
# 43.0
- Don't use deprecated API; Hide 'Allow parallel run' checkbox (#4331)
- Fix Inspector and WidgetRebuildIndicators for bazel projects (#4302)
- Simplify flutter-intellij project setup for new contributors (#4330)
- support 2020.1 EAP (#4335)
- Define dev channel artifacts (#4328)
- Simplify the logic we use to prevent reload on save (#4327)
- Don't use deprecated DartAnalysisServerService.serverReadyForRequest(Project) (#4332)
- Separate build vs test scripts (#4326)
- Update the dart plugin to IntelliJ 2019.2 (#4324)
- Refactor fix (#4321)
- Refactor build script (#4320)
- Check pre-reqs for build (#4308)
- Make build script executable (#4306)
- Defend against invalid refresh rates for flutter desktop devices (#4299)
- Kokoro build configuration (#4280)
- Increase default memory usage to make testing the Flutter plugin on large projects more pleasant (#4300)
- Revert "Update error message to suggest the typical solution (#4219)" (#4303)
- Cleanup update after dispose edge cases (#4301)
- Fix an issue with sending in non-absolute paths to flutter.subscriptions (#4275)
- Switch to using WorkspaceCache (#4295)
- Don't process refresh requests for app's which have terminated (#4294)
- Restrict checkbox selectable region in performance window (#4292)
- Restore ability to use Java 11 (#4290)
- Remove hard coded refresh rate for fps calculation (#4289)
- Address a concurrent modification exception in the widget build count code (#4283)
- Tweak the text for a UI setting (#4288)
- Add an 'Open Dart DevTools' menu item (#4284)
- Change assert to null check and return (#4274)
- Build dev channel (#4267)
- Avoid creating RunContentManager (#4271)
- Refactor the reload on save implementation (#4247)
- Draw a separator line between the main inspector tree and the details tree (#4253)
- Format source and remove unused imports (#4250)
- Fix an npe related to hot ui (#4249)
- Fail gracefully if there is not an active file just as we fail gracefully if there is no outline (#4220)
- Rename a flutter refactor action (#4237)
- Fix an issue with the pub notification showing when things were already up to date (#4239)
- Generate dev log (#4213)
- Fix NPE in add-to-app support (#4207)
- Launch flutter attach when the Android app starts (#4200)
- Update error message to suggest the typical solution (#4219)
- If track widget creation is not enabled, pass in --no-track-widget-creation (#4196)
- Surface reload exceptions (#4198)
- Provide more stack trace details for inspector timeouts (#4193)
## 42.2
- Support Android Studio 3.6 RC 1
## 42.1
- Enable Hot UI for Flutter Interact
- Fix two NPEs from the outline view (#4188)
- Fix an NPE from CommonTestConfigUtils.getTestsFromOutline (#4184)
## 42.0
- Hot UI implementation (#4160)
- Support new Inspector select api and a few other minor tweaks (#4158)
- Services to manage tracking inspector and editor events more effectively
- Support Inspector APIs needed for HOTUI (#4153)
- Smooth out the rough spots in add-to-app support (#4129)
- Remove an unused field (#4152)
- Switch getWidgetDescription to use CompletableFuture as it sometimes takes more than 100ms (#4151)
- Update the product matrix for 2019.3 stable (#4148)
- Fix an NPE in PubRoot.forDescendant (#4147)
- Remove FlutterSampleManager; for embedded flutter samples, open the hosted docs (#4139)
- Make the async rate limiter implementation a bit more robust (#4144)
- Refactor of Color parsing code to share more logic with HotUI (#4141)
- Show error dialog when creating a project with canary builds (#4140)
- Misc test cleanup (#4138)
- Add null check to guard against missing property (#4135)
- Add some more logging information to help diagnose the 'method not found' errors (#4125)
- Force VFS refresh to prevent adding multiple include statements (#4126)
- Fix an npe when getting the target fps for a device (#4124)
- Add missing Nullable annotation (#4122)
- Remove the two secondary UI guides settings (#4121)
- Allow defining location of Android add-to-app modules (#4117)
- Use a LinkLabel for the privacy link in the settings page (#4120)
- Fix cases where ActiveEditorsOutlineService was not thread safe (#4119)
- Refactor the UI and location of the Flutter Performance tool window (#4111)
- Support removing widget property values (#4118)
- Build for Android Studio beta 4 and later (#4109)
- Support for debugging add-to-app modules in Android Studio (#4097)
- Update FlutterDartAnalysisServer to support Widget manipulation methods (#4102)
- Improve devtools launching (#4105)
- Reduce the severity of a warning (#4107)
- Address an 'Unknown platform' message in the IntelliJ log (#4104)
- Address a npe / race condition in StdoutJsonParser.java (#4101)
- Remove support for package:flutter_web (#4088)
- Don't try to format a read only doc (#4098)
- Address a disposable issue (#4094)
- Add more diagnostics for an error (#4092)
- Silence a log warning (#4091)
- Use NotNull and remove an if check (#4087)
- Address a resource leak on shutdown (#4074)
- Fix a null assertion (#4076)
- Remove a System.out.print reference (#4075)
- Address an npe in FlutterConsole.java (#4077)
- Misc cleanup to the HeapMonitor class (#4078)
- Add diagnostics for 'Runner must be specified' error (#4068)
- Prevent an exception related to use of a disposed Alarm (#4071)
## 41.1
- Adjust build range for AS beta 3 (#4061)
- Fix error from undefined macro (#4056)
## 41.0
- Remove support for file path breakpoints; handle multiple vm breakpoints better (#4019)
- Force Android Studio to show the Project view (#4031)
- Build for ADS4 canary 1 (#4017)
- Check for project disposed during format on save (#4022)
- Remove an Observatory link handler from DartVmServiceDebugProcess.java (#4018)
- Detect whether the VM service connection supports the getMemoryUsage API (#4016)
- Don't invoke eval when shutting down (#4015)
- Re-enable our disabled tests (#4013)
- Co-edit module created in Android Studio (#4004)
- Address several warnings in the IntelliJ log about leaked resources (#3999)
- Remove an unused method (#4009)
- Update CONTRIBUTING.md
- Change the inspector tool window to not only show when an app is running (#4000)
- Remove the Performance tab from the Inspector; remove Observatory actions (#4008)
- Hide the custom logging view setting (#4005)
- Fix a project assert in the Flutter editor notification (#3994)
- Address a few warnings about 'mostly idle daemon process' (#3995)
- Add more info to eval() exceptions (#3992)
- Fix an NPE when switching platforms (#3990)
- Fix an NPE in the feedback button (#3989)
- Rename two wrap with Flutter actions (#3988)
- Remove support for the older `_Logging` event (#3986)
- Various bits of code cleanup (#3981)
- Remove two reload and restart keybindings (#3979)
- Fix the offset of console hyperlink detection (#3978)
- Fix an issue where non-ephemeral device selection wouldn't persist (#3977)
## 40.2
- Increase version range for AS 3.6 beta 1 (#3973)
- Fix NPE in when querying display refresh rate (#3927)
- Fix a ConcurrentModificationException from ActiveEditorsOutlineService (#3954)
- Ignore errors from `app.stop` (#3957)
## 40.1
- Unhook Gradle listeners from IntelliJ (#3941)
- Fix a ConcurrentModificationException (#3939)
## 40.0
- Change args to work with new defaults of flutter create (#3902)
- Fix the changelog markdown translation (#3904)
- Use the new getMemoryUsage() API (#3877)
- Turn on the detailed test output by default for Bazel (#3876)
- Query display refresh rate and use in Performance window (#3890)
- Fix an NPE in FlutterIconProvider.java (#3893)
- Remove use of some deprecated calls (#3886)
- Build for 2019.3 EAP and 3.6 canary 11 (#3872)
- Update to latest version of VmService (#3889)
- Fix merge error (#3888)
- Support co-editing Flutter and Android in a single project (#3850)
- Replace some deprecated API calls (#3875)
- Add build actions (#3868)
- Add auto-edits of iml (#3870)
- More normalization of flutter error codes (#3866)
- Fix a couple AS issues (#3864)
- Fix a ConcurrentModificationException in FlutterSdk.getFlutterSdk() (#3863)
- Address instances of process execution on the EDT (#3858)
- Fix open widget sample opening only counter sample app (#3854)
- Add Hide Notification hyperlink to Notification Panel (#3761)
## 39.0
- Changed project creation to default to AndriodX deselected until it works for Flutter modules
- Enabled structured errors by default
- Fix #3731: Synchronous execution on EDT (#3823)
- Make the new languages be default (#3819)
- Don't call reload for the unforked flutter web impl (#3816)
- Perform additional normalization on flutter error codes (#3813)
- Fix an issue related to the error reporter (#3811)
- Improve computeDefaultPresentation (#3803)
- Convert an error to a warning (#3810)
- Fix ArrayIndexOutOfBounds for target platform selector (#3809)
- Flutter web inspector (#3792)
- Rev to the latest vm service library (#3801)
- Adapt to API changes in ASc6 (#3802)
- Switch to using the VM Service directly instead of the Daemon protocol when invoking service extensions (#3790)
- Update no-response.yml (#3789)
- Upgrade the version of the dart plugin that we compile against (#3784)
- Address a setPreferredFocusableComponent() warning in the IntelliJ log (#3783)
- Fix a regression in the Flutter Outline view (#3782)
- Cache the results of parsing the pubspec file (#3773)
- Only parse analysis server events we're interested in (#3772)
- Optimize FlutterUtils.isInTestDir (#3774)
- Add platforms to testing matrix (#3768)
- Make part of the dart code use implicit-casts false (#3762)
## 38.2
- Fix bug on Windows that prevented outlines from displaying
- Restore the ability to run individual tests
- Fix a couple other issues
## 38.1
- Fix first-time installation issue
## 38.0
- Add AndroidX option to new project wizards (#3705)
- Fix break due to Android Studio 3.6 API change (#3712)
- Fix logger npe (#3711)
- Integration test update (#3710)
- Fix highlighting of project descriptions (#3709)
- Re-enable tests on the bots (#3702)
- Update the flutter error display (#3682)
- Relabel 'samples'to 'widget samples' (#3701)
- Address some issues with blocking the EDT thread in 2019.2 (#3700)
- Remove the web/desktop user preference (#3698)
- Fix the logging tests (#3699)
- Use DAS test annotations to flag runnable tests (#3662)
- Add short-lived prompt for Q3 user survey (#3691)
- Add a user preference to opt-in to showing structured errors (#3692)
- Add target platform selector for togglePlatform service extension (#3688)
- Update the widgets.json catalog file (#3687)
- Restore stack traces in generated error reports (#3685)
- Make the event stream tests pass and re-enable them (#3684)
- Init default settings for the run console text wrapping (#3661)
- Send flutter.error analytics (#3659)
- Remove extra console whitespace (#3660)
- Fix an issue with some daemon json output appearing in the console (#3658)
- Initial work on displaying Flutter.Error events (#3644)
- Show truncated logging messages (#3641)
- Name the Bazel test config factories to match assumed names in g3 (#3636)
- Remove no longer used functionality related to restart warnings (#3645)
- Fix per SDK Stream<Uint8List> breaking changes (#3640)
- Fix New Pproject Wizard (#3631)
- Adjust the text for the desktop/web device preference (#3629)
- Issue 3615. Fix message for 'Remove widget' (#3622)
- Support showing desktop and web devices (#3618)
## 37.0
- Fix an offset issue with the UI guides code (#3574)
- Add IDE query param to DevTools url. (#3592)
- Treat FlutterApp as a long-running process (#3599)
- Fix links for test URLs (#3600)
## 36.0
- Add Gradle build script (#3529)
- Update for new platform releases (#3527)
- Add in a preference to toggle closing labels (#3528)
- Don't disable closing labels as part of UI Guides (#3525)
- Enable devtools launching from Bazel (#3511)
- Guard against null project basedir (#3524)
- Change DeviceDaemon to show a detailed error when it fails too many times. (#3513)
- Add an inline run menu option to run or watch Bazel Flutter tests (#3507)
- Make the save dialog refer to the save all action, not the save action (#3505)
- Introduce an opt-in detailed test runner for Bazel tests (#3451)
- Remove the android studio specific memory view (#3497)
- Limit the amount of time we wait for a graceful app shutdown (#3490)
- Mark the device daemon process as a background process (#3488)
- Fix errors in AS 3.5 beta 1 (#3487)
- Remove the preview view from the flutter outline view (#3481)
- Remove a println in WidgetIndentsHighlightingPass.java (#3468)
- Fix an npe from the FlutterErrorReportSubmitter.java class (#3469)
- Handle notifications when a project has been disposed more gracefully. (#3472)
- Fix two bugs for widget guide outlines. (#3470)
## 35.1.3
- Support IntelliJ 2019.1.2 RC
- Support Android Studio 3.5 beta 1
- Bug fixes
## 35.1
- Add an option to hide closing labels in Dart source code when UI guides are on (#3438)
- Create "Editor" section of Flutter Settings (#3434)
- Support UI as Code Widget Guides (#3420)
- Add checkbox to skip the dart analyzer error check before a hot reload (#3414)
- Remove the option to disable the memory view from the settings (#3408)
- Track API changes (#3427)
## 35.0
- Sample panel layout improvements (#3396)
- Remove unneeded logging (#3394)
- Java analysis lints cleanup (#3395)
- Update subscriptions after analysis server restart (#3393)
- Read sample index from flutter_tool call (#3379)
- Update README (#3387)
- Fix unit tests
- Update build for canary 11 (#3380)
- Integration test update (#3374)
- Make the inspector easier to test (#3373)
- Adjust build to make plugin for testing (#3366)
- Address reported Java lints (#3356)
- Adjust build for AS canary 10
- Address an array index out of bounds (#3355)
- Address an NPE (#3354)
- Upgrade the service protocol library (#3353)
- Address a number format exception (#3352)
- Update how we manipulate the service protocol url (#3351)
- Remove some uses of reflection (#3350)
- Some initial work for FlutterWeb apps (#3342)
- Fix an NPE when sample content generation is disabled (#3336)
- Add inspector dependency to test (#3316)
- Make Dart constructor calls pop out in light mode (#3327)
## 34.0
- Update build for Android Studio 3.3.2 and IntelliJ 2019.1 (#3321)
- Fix issue preventing plugin from working in AS Canary 8 (#3321)
- Provides a better display if the variable has a `toStringDeep()` method defined. (#3291)
- Don't show a background square in the inspector summary tree. (#3326)
- Make FlutterModuleUtils consistently robust to disposed projects. (#3323)
- Fix NPE issue sometimes hit evaluating expressions. (#3324)
- Fix widget names. (#3322)
- Make Perf and Inspector views only display when a Flutter app is being debugged. (#3320)
- Support the inspector for flutter_web libraries. (#3310)
- Detect when integrations tests are running (#3308)
- Add in support for reloading and restarting all running apps (#3268)
- Log tree path selection fixes (#3302)
- Throttle logger updates (#3280)
- New method in FlutterUtils: declaresFlutterWeb, this method checks for dependencies: fluttler_web in a pubspec file. (#3275)
- Update a comment in FlutterSaveActionsManager (#3277)
- Remove the second parameter (the Project) from SdkFields constructor, it isn't used anymore. (#3261)
- Add a comment to a recent change (#3267)
- Fix a file handle leak (#3264)
- Port inferPubRootDirectoryIfNeeded from devtools (#3242)
- Add support for matching customized Widget tests. (#3249)
- Hide DevTools debugger when launching from IntelliJ. (#3252)
- Migrate to GearPlain (#3248)
- Minor cleanup (#3247)
- Inline sample index reading (#3245)
- Make a newer daemon protocol field optional (#3230)
- Link to the plugins readme file from the building instructions. (#3222)
## 33.3
- Fix an issue with an IllegalArgumentException when running Flutter apps
## 33.2
- Support IntelliJ 2018.3.3
## 33.1
- add menu and toolbar button to open Flutter DevTools
- fix Gradle sync issue for Android Studio 3.3.1
- fix highlighting of the Go link in sample banner
## 33.0
- update build for Android Studio 3.3.1
- reorder console filters so links work
- more intelligently enable support for detaching from Flutter apps on exit
- change the icon used for paint baselines
- prevent bazel test run configurations from generating in a non-bazel workspace
- support 2019.1 eap
- mention 'Dart' in the plugin description
- correct the bazel output for debugging bazel tests
- simplify the bazel parameters we pass to Bazel Run configurations
- pin flutter error events in the log
- propagate node selections to inspector
- link support for log data entries
- fix category cell rendering
- add sample creation banner
- add sample apps to Android Studio New Project Wizard
- update log entry data badge
## 32.0
- address an NPE in FlutterWidgetPerfManager.java
- added overlay renderered for GC, snapshot and memory reset events
- consolidated all adt-ui API changes in FlutterStudioMonitorStageView
- support for creating projects w/ sample content from the IDEA New Project Wizard
- basic ansi color support for entries in the Flutter Logging View
- restore log level combo to the Logging View
- support to fill in truncated log entries
- add keyboard shortcut for widget extraction
- add debugPaint and debugAllowBanner icons
- add repaint rainbow icon
- handle cases where script.tokenPosTable is null
- auto-hide details pane
- guard against disposed when querying project type
- fix an issue with escaped test names
- refactor service extensions and set button text based on extension state
- shorten message for debug mode perf disclaimer
- listen for ServiceExtensionStateChanged events
- restore service extension states from device on start and attach
- don't use LOG.error()
- refactor the Bazel Test configuration to support running tests on a single file or a single test
- fix enabled/disabled text for service extensions
- fix NPE in bazel config
## 31.3
- fix NPE in sdk installation (#2965)
- fix NPE caused by internal inconsistency (#2963)
## 31.2
- show memory profiler legend with proper line chart color or line style
- prevent the (IntelliJ) New Project wizard from completing when there is no Flutter SDK
- fix a race condition causing unexpected conditions in attach
- added control of RSS display to memory profiler
- when running the flutter doctor command, use the -v flag
- make attach use selected device
## 31.1
- perf table polish and fix links to tip docs
- fix Split Mode resize issue
- rebuild stats wording tweaks
## 31.0
- change FPS display to "Frame Rendering Time" and improve UI
- reorganize inspector tools
- better error reporting for Flutter runtime issues
- fewer Flutter runtime issues
- updated icons for Material and Cupertino
- searchable preferences/settings
- added refactoring to outline view: extract widget
- new menu item to run 'flutter make-host-app-editable'
- code cleanup and bug fixes
## 30.0
- performance inspector changes
- log view tweaks
- memory profiler updates
- support 'flutter attach' in the IDE (both IJ and AS)
- support offline project creation in the AS wizard
- code cleanup and bug fixes
## 29.1
- address an issue with an NPE when debugging
## 29.0
- add 'Wrap with Container' to preview
- fix test navigation
- clear log on restart
- experimental memory profiler; enable in preferences
- build for 2018.3 EAP
- bug fixes
## 28.0
- build for Android Studio 3.3 Canary and 3.2 Beta
- add UI support for importing Flutter modules into Android apps
- add more details to logging output
- bug fixes
## 27.1
- change the preference for --track-widget-creation to default to off
## 27.0
- add a setting to control syncing Android libraries
- fixes related to evaluating expressions when not on a call frame
- auto-disable scroll to end when the user manually scrolls the log up
- add the "module" template to new-module and project wizards in Android Studio
- improve copy / paste in the Logging View
- some tweaks to the open in Android Studio functionality
- validate android package names
- add Android module libraries to Flutter projects
- validate org in the project wizard
- default log coloring to on and update logger defaults
- fix log entry browser links
- support hyperlinks in flutter console log
- add InheritedWidget and Stateful Widget with Animation live templates
- lower case the log level names
## 26.0
- updates to support Android Studio 3.2 Beta
- removes the Inspector's empty content message
- support setting log color from flutter log settings page
- support hiding/showing log categories (#2398)
- add flutter log color settings page (#2394)
- change the default for the open inspector setting
- look for the emulator tool in the 'emulator/' directory first (#2383)
- support filtering by log level (#2380)
- fix the flutter log view while resizing (#2379)
- log entry coloring (#2382)
- log tree rendering refactor (#2381)
- for BazelRunConfig launches, print the command-line to the console (#2368)
- refactor the Flutter debugging client code (#2359)
- support match case/regex filter in log view (#2350)
- fix auto-scroll to catch up to fully rendered log tree (#2342)
- use the log category name from the dart:developer event (#2339)
- fix-up missing create project mnemonics (#2326)
- handle reload errors (#2321)
- fixes for the native editor banner
## 25.0
- remove the user preference to disable --preview-dart-2
- don't use 'new' for the stless, stfull, stanim templates
- add support for IntelliJ 2018.2 EAP (#2270)
- added a new (very experimental) logging view
- update the extract widget refactoring visibility (#2251)
- launch a simulator device if none is running (#2234)
- improvements to the preview view on Windows (#2239)
- open the selected file for editing when opening a new project (#2236)
- open selected file when launching Android Studio (#2230)
- add a command bar to editors that can open in a native-code editor (#2216)
- rename full restart to hot restart (#2225)
## 24.2
- fix the --track-widget-creation flag implementation on Windows
- fix for an exception in the Outline view on older Flutter SDKs
## 24.1
- update Flutter icons
- fix an exception when the selection changes and the outline view isn't visible
- fix for an issue with reload on save in profile runs
- fix for a 2017.3 issue with a 'no running apps' message in the inspector
## 24.0
- inspector: significant UI refactoring to show the tree in a master / details format
- inspector: add a 'Performance' tab to the Inspector, to show application FPS and memory usage
- inspector: fix issues turning --track-widget-creation on and off
- inspector: handle apps with multiple isolates in the inspector
- live preview: suggest 'Add forDesignTime() constructor' for widgets
- live preview: make the preview area smaller if the widget is not renderable
- live preview: fixes to make outline preview working on Windows
- live preview: sort children outlines by their RenderObject.depth during preview
- simplify how we recognize Flutter projects when using Bazel
- fix the "Open in Android Studio" action to not show for the ios dir
- add an option to create projects in “offline” mode
- better support for using multiple Flutter modules per IntelliJ project
- improvments to the "Open in XCode…" menu item
- better support for importing Flutter projects
- several fixes for issues with using resources that had been disposed
- add local history labels on reloads and restarts
- have the 'reloading...'' notification timeout after the reload completes
- improved support of running in --profile mode
- expose the new 'Extract Widget' refactoring
## 23.2
- updated some Bazel breakpoint logic
## 23.1
- disabled an Android facet's ALLOW_USER_CONFIGURATION setting, to address a continuous indexing issue
## 23.0
- outline view: removed the experimental flag
- outline view: filter the outline view to only show widgets by default
- inspector: several stability and polish improvements
- inspector: now supports inspecting multiple running apps at the same time
- we now show material icons and colors in code completion (requires 2017.3 or AS 3.1)
- running and debugging flutter test adding for Bazel launch configurations
- added an 'Extract method' refactoring
- the preview dart 2 flag can now accept the SDK default, be set to on, or set to off
- Android Studio: we now support 3.1
- Android Studio: fixed an issue where Android Studio was indexing frequently
- experimental: added a live sparkline of the app's memory usage
- experimental: added a live preview area in the Outline view
- experimental: added the ability to format (and organize imports) on save
## 22.2
- when installing the Flutter SDK, use the 'beta' channel instead of 'dev'
## 22.1
- when installing the Flutter SDK, use the 'dev' channel instead of 'alpha'
- fix an issue with the Flutter Outline view on Windows
## 22.0
inspector view:
- support for multiple running applications
- basic speed search for the Inspector Tree
- restore flutter framework toggles after a restart
- expose the observatory timeline view (the dashboard version) (#1744)
- live update of property values triggered each time a flutter frame is drawn. (#1721)
- enum property support and tweaks to property display. (#1695)
- HD inspector Widgets (#1682)
- restore inspector splitter position (#1676)
- open the inspector view at app launch (#1670)
outline view:
- rename 'Add widget padding' assist to 'Add padding' (#1771)
- bind actions to move widget down/up. (#1768)
- rename 'Replace with children' to 'Remove widget'. (#1764)
- add action for 'Replace with children' assist. (#1759)
- update messages for wrapping with Column/Row. (#1745)
- add icons and actions for wrapping into Column and Row. (#1743)
- show build() methods in bold (#1731)
- associate the Center action with the corresponding Quick Assist. (#1726)
- navigate from source to Preview view. (#1710)
- add speed search to the Preview view. (#1696)
- add basic Flutter Preview view. (#1678)
platforms:
- support 2018.1 EAP
- no longer build for 2017.2
miscellaneous:
- fix for displaying the flutter icon for flutter modules
- fix for issue 1772, Switch Bazel flag for launching apps (#1775)
- add support for displaying flutter color shades in the editor ruler (#1770)
- add a flag to enable --preview-dart-2 (#1709)
- smarts to run `flutter build` before trying open Xcode (#1373). (#1694)
- harden error reporting on iOS simulator start failures (#1647). (#1681)
## 21.2
- Fix an NPE when the Flutter SDK version file contains the text 'unknown'
## 21.1
- Fix an NPE when reading the Flutter SDK version file
## 21.0
- select an existing config at launch
- fix test discovery for plugin example tests
- fix discovery of tests in example subdirs
- improve pub root detection for flutter tests
- actionable “restart” debugging console output
- improve console hyperlinking for local files
- fix run config autoselection for plugin projects
- for non-bazel project configurations, don't show the FlutterBazelRunConfigurationType
- update FlutterViewCondition to be bazel project aware
- remove the preference for the Inspector view (it's now on by default)
- rename the Flutter view to Flutter Inspector
- clean up of the Flutter Inspector View icons
- show color properties with a nice color swatch icons
- add a notification for reloaded but not run elements
- show flutter material icons in the inspector
- for Bazel launch configurations, update the android_cpu architecture type from armeabi to armeabi-v7a
## 20.0
- improved console filtering
- improved unit test running support to allow running package:flutter tests
- improved "Open with Xcode..." logic to work better for plugin projects
- fixed project creation to properly respect custom creation options (such as target language)
- fixed an NPE sometimes encountered when deleting projects
## 19.1
- Bazel run configuration updates
## 19.0
- fixed an issue with reload when multiple project windows are open
- fixed running Flutter tests in nested groups
- fixed miscellaneous project wizard issues
- fix to ensure we don't create Flutter library entries for non-Flutter projects
- fixed project name validation in the new project creation wizard to be more performant
- fixed project opening to only open main.dart if no other editors are open
- fix to limit Flutter icon contributions to Flutter projects
- reload on save updated to ignore errors in test files
- IDEA EAP support
- fix to give restarted apps focus on iOS
- miscellaneous Android Studio support fixes
- fixed check for Flutter tests to not mis-identify vanilla Dart tests
- improved error reporting on project creation failures
## 18.4
- Revert to 18.1 to address an NPE in the FlutterInitializer class
- fixed an issue where reload on save could not be disabled
## 18.3
- fixed a build problem that prevented the Android Studio plugin from creating projects
## 18.2
- fixed an issue where reload on save could not be disabled
- fixed an exception that could occur on project creation
## 18.1
- fixed hot reload issue when multiple project windows were open
- fixed 'Open Observatory timeline' action
## 18.0
- Android Studio support
- for flutter launches, support passing in a --flavor param
- reload on save now on by default
- improved and reorganized the Flutter view's toolbar
- analysis toast provides a new hyperlink to open the analysis view
- reloads disallowed while another reload is taking place
- support to show referenced flutter plugin in the project view
## 17.0
- improved new project wizard
- improvements to the reload-on-save behavior
- improved and reorganized the Flutter view's toolbar
- fixes to the Flutter icon decorations in the editor ruler
- fixes to group handling for widget tests
- display a ballon toast if there are analysis issues when running apps
- added a toggle inspect mode toolbar button
- speed improvements to the device switcher pulldown
## 16.0
- device list refresh fixes
- support for flutter run in profile and release modes
- support for reading the android sdk location from flutter tools
- support for discovering and running Flutter widget tests
- Flutter test console improvements
- support for running flutter doctor in a Bazel workspace
- test file icon annotations
- support for locating a missing flutter SDK in .packages files
- open emulator action sorting
- test state icons for Flutter tests
- editor line markers for Flutter tests
- added a new restart daemon action
- open emulator action sorting
- run/debug button enablement improvements
- fix to ensure the `Install SDK…` action is always visible
- support for running a single Flutter test, by name
- install creation progress UI fixes
- project creation fixes for small IDEs
- fixes to android emulator launching
## 15.2
- fix for an exception in the new project wizard in WebStorm (#1234)
## 15.1
- fix for a file watching related NPE on build systems using Bazel (#1191)
## 15.0
- UI for starting android emulators from the device pull-down
- workflow for installing a Flutter SDK from the New Flutter Project wizard
- Flutter SDK configuration inspection improvements
- improved error reporting on project creation failures
- improved app reload feedback
- Flutter View toolbar tweaks
- initial support for running unit tests with `flutter test`
- new action to open iOS resources in Xcode
## 14.0
- user toggleable option to enable more verbose debug logging of Flutter app runs
- fixes to the new Flutter Module workflow
- improved console logging on Flutter app termination
- improved error reporting on Observatory connection and Flutter View open failures
- removed Flutter SDK settings from default projects
- improved project name validation (to align with checks in `flutter create`)
- console hyperlinks for Xcode resources
- fix to inherit Android JDK setting when creating Flutter projects
- fix to ensure Flutter console filtering is only applied to Flutter consoles
- improved device daemon interop
- improved SDK version checking
## 13.1
- project opening improvements
- new action to open the Flutter view
- module name validation on creation
- fix to ensure all open files are saved to disk before running Flutter actions
- improved progress reporting during calls to 'flutter create'
- miscellaneous fixes and analytics improvements
## 13.0
- small IDE support improvements
- android module enablement on project creation
- project explorer icon customizations
- support for Flutter drop frame debugging
- hot reload UX improvements
- Bazel run config refinements
- support for toggling OS in the Flutter View
- Flutter CLI interop fixes (proper env setup)
- color icon improvements
- bump to require 2017.1+
## 12.1
- fix an issue with enabling Dart support for modules from the Flutter settings page
## 12.0
- support for IDEA `2017.1`
- new Flutter `stless`, `stful`, and `stanim` live templates
- new assists for editing the widget hierarchy:
- move widget up or down
- re-parent widget or list of widgets
- convert `child:` keyword to `children:`
- support for specifying "Additional Args" to Flutter application launches
- default run configuration creation on project open (when possible)
- device menu improvements
- miscellaneous bug fixes
## 0.1.11.2
- fix an NPE in the Flutter View when launching an app
## 0.1.11.1
- fix to a use after dispose exception in the Flutter View
## 0.1.11
- Flutter tool window badging when active
- iOS console output folding improvements
- Flutter reload actions added to main "Run" menu
- devices menu fixes
- improved tooltips for pubspec editor notifications
## 0.1.10
- fixes to pubspec timestamp checking
- analytics events for run, debug, and process stop
- fix to `flutter doctor` to better support multiple runs
- fix to the reload action for apps launched from 'run'
## 0.1.9.1
- fix button enablement in the Flutter View
- fix the reload action for apps launched from 'run'
## 0.1.9
- added a 'Flutter' view to allow users to toggle Flutter framework debugging features while running
- fixes to the visibility of the "Tools" menu
- inspection to detect pubspec modifications (that may imply out of date package dependencies)
- key bindings fixes
- support for opening source folders as Flutter projects (using "Open...")
- run and debug button enablement fixes
- fix to bring iOS simulator to front on run/debug
- fix to handle devfs breakpoints for projects without pubspecs
## 0.1.8.1
- improve handling of breakpoints for the bazel launch config
## 0.1.8
- fixed race condition in console reporting on project creation
- improved interaction between Flutter and Dart plugins during project creation (no more unnecessary nags to run pub)
- improvements to version checking
- settings UI refinements
- new "Help > Flutter Plugin" top-level menu
- added reload/restart actions in the main toolbar
- improved console folding for iOS messages
- fixed NPE in project creation
## 0.1.7
- improved console output folding when running iOS apps
- actions for Flutter package get and package update
- a new top level Flutter menu (Tools>Flutter) with common Flutter actions
- updated hot reload and restart icons
- editor annotations showing Flutter colors and icons in the editor ruler
- better console filtering (less noise)
- improved detection of Flutter projects missing a Flutter module type
## 0.1.6
- reload and restart keybinding mapping fixes
- new butter bar with actions for flutter.yaml files
- "run" behavior re-designed to support reload
- improved console output for reloading and restarting
- miscellaneous fixes and stability improvements
## 0.1.5
- console filtering for flutter run output
- improved messaging for incomplete Flutter SDK configurations
- support for new application events produced by Flutter tools
- fixed duplicate service protocol console logging
- Flutter run configuration cleanup
- fixed NPE in showing progress from Flutter tools tasks
- migration away from storing Flutter SDK location in an application library
## 0.1.4.1
- removed an exception notification when we receive unknown events from the flutter tools
## 0.1.4
- first public release
## 0.1.3
- notifications for projects that look like Flutter apps but do not have Flutter enabled
- improved Flutter preference UI and SDK configuration
- IDEA version constraints to ensure that the plugin cannot be installed in incompatible IDEA versions
## 0.1.2
- fixed device selector filtering
## 0.1.1
- removed second (redundant) "open observatory" button
- filtering to ensure the Flutter device selector only appears for Flutter projects
- fixed hangs on app re-runs
## 0.1.0
- initial alpha release
| flutter-intellij/CHANGELOG-old.md/0 | {
"file_path": "flutter-intellij/CHANGELOG-old.md",
"repo_id": "flutter-intellij",
"token_count": 15774
} | 487 |
<idea-plugin>
<version>1.0-SNAPSHOT</version>
<change-notes>Created the plugin. Added UI Tests for the Flutter plugin.</change-notes>
<id>io.flutter.tests.gui.flutter-gui-tests</id>
<name>Flutter UI Tests</name>
<description>
Plugin should be used only for internal purposes.<br>
<em>Do not distribute this plugin with Flutter</em>
</description>
<depends optional="true">com.intellij.testGuiFramework</depends>
<depends>io.flutter</depends>
<vendor>flutter.io</vendor>
<extensions defaultExtensionNs="com.intellij"/>
<actions/>
</idea-plugin>
| flutter-intellij/flutter-gui-tests/res/META-INF/plugin.xml/0 | {
"file_path": "flutter-intellij/flutter-gui-tests/res/META-INF/plugin.xml",
"repo_id": "flutter-intellij",
"token_count": 219
} | 488 |
/*
* Copyright 2020 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.
*/
package io.flutter.actions;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.Project;
import icons.FlutterIcons;
import io.flutter.run.daemon.DeviceService;
import io.flutter.utils.FlutterModuleUtils;
import org.jetbrains.annotations.NotNull;
public class DeviceSelectorRefresherAction extends AnAction {
public DeviceSelectorRefresherAction() {
super(FlutterIcons.RefreshItems);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final Project project = e.getProject();
if (project != null) {
DeviceService.getInstance(project).restart();
}
}
public @NotNull ActionUpdateThread getActionUpdateThread() {
return ActionUpdateThread.BGT;
}
@Override
public void update(@NotNull AnActionEvent e) {
if (e.getProject() != null) {
e.getPresentation().setVisible(FlutterModuleUtils.hasInternalDartSdkPath(e.getProject()));
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/DeviceSelectorRefresherAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/DeviceSelectorRefresherAction.java",
"repo_id": "flutter-intellij",
"token_count": 363
} | 489 |
/*
* Copyright 2017 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.
*/
package io.flutter.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.project.Project;
import io.flutter.android.AndroidEmulator;
import io.flutter.sdk.AndroidEmulatorManager;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class OpenEmulatorAction extends AnAction {
/**
* Retrieve a list of {@link OpenEmulatorAction}s.
* <p>
* This list is based off of cached information from the {@link AndroidEmulatorManager} class. Callers
* who wanted notifications for updates should listen the {@link AndroidEmulatorManager} for changes
* to the list of emulators.
*/
public static List<OpenEmulatorAction> getEmulatorActions(Project project) {
if (project == null || project.isDisposed()) {
return new ArrayList<>();
}
final AndroidEmulatorManager emulatorManager = AndroidEmulatorManager.getInstance(project);
final List<AndroidEmulator> emulators = emulatorManager.getCachedEmulators();
return emulators.stream().map(OpenEmulatorAction::new).collect(toList());
}
final AndroidEmulator emulator;
public OpenEmulatorAction(AndroidEmulator emulator) {
super("Open Android Emulator: " + emulator.getName());
this.emulator = emulator;
}
@Override
public void actionPerformed(@NotNull AnActionEvent event) {
emulator.startEmulator();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/OpenEmulatorAction.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/OpenEmulatorAction.java",
"repo_id": "flutter-intellij",
"token_count": 503
} | 490 |
/*
* Copyright 2017 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.
*/
package io.flutter.actions;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.wm.ToolWindowId;
import io.flutter.FlutterBundle;
import io.flutter.run.FlutterLaunchMode;
public class RunProfileFlutterApp extends RunFlutterAction {
public static final String TEXT = FlutterBundle.message("app.profile.action.text");
public static final String DESCRIPTION = FlutterBundle.message("app.profile.action.description");
private static final String TEXT_DETAIL_MSG_KEY = "app.profile.config.action.text";
public RunProfileFlutterApp() {
super(TEXT, TEXT_DETAIL_MSG_KEY, DESCRIPTION, AllIcons.Actions.Execute, FlutterLaunchMode.PROFILE, ToolWindowId.RUN);
}
}
| flutter-intellij/flutter-idea/src/io/flutter/actions/RunProfileFlutterApp.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/RunProfileFlutterApp.java",
"repo_id": "flutter-intellij",
"token_count": 264
} | 491 |
/*
* Copyright 2017 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.
*/
package io.flutter.bazel;
import com.google.common.base.Objects;
import com.google.common.collect.ImmutableSet;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.registry.Registry;
import io.flutter.FlutterUtils;
import io.flutter.project.ProjectWatch;
import io.flutter.utils.FileWatch;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.Objects.requireNonNull;
/**
* Holds the current Bazel workspace for a Project.
* <p>
* <p>Automatically reloads the workspace when out of date.
*/
public class WorkspaceCache {
@NotNull private final Project project;
@Nullable private Workspace cache;
private boolean disconnected = false;
private boolean refreshScheduled = false;
private final Set<Runnable> subscribers = new LinkedHashSet<>();
private WorkspaceCache(@NotNull final Project project) {
this.project = project;
// Trigger a reload when file dependencies change.
final AtomicReference<FileWatch> fileWatch = new AtomicReference<>();
subscribe(() -> {
if (project.isDisposed()) return;
final Workspace next = cache;
FileWatch nextWatch = null;
if (next != null) {
nextWatch = FileWatch.subscribe(next.getRoot(), next.getDependencies(), this::scheduleRefresh);
nextWatch.setDisposeParent(project);
}
final FileWatch prevWatch = fileWatch.getAndSet(nextWatch);
if (prevWatch != null) prevWatch.unsubscribe();
});
// Detect module root changes.
ProjectWatch.subscribe(project, this::scheduleRefresh);
// Load initial value.
refresh();
}
private void scheduleRefresh() {
if (refreshScheduled) {
return;
}
refreshScheduled = true;
SwingUtilities.invokeLater(() -> {
refreshScheduled = false;
if (project.isDisposed()) {
return;
}
refresh();
});
}
@NotNull
public static WorkspaceCache getInstance(@NotNull final Project project) {
return requireNonNull(project.getService(WorkspaceCache.class));
}
/**
* Returns the Workspace in the cache.
* <p>
* <p>Returning a null means there is no current workspace for this project.
*/
@Nullable
public Workspace get() {
return cache;
}
/**
* Returns whether the project is a bazel project.
*/
public boolean isBazel() {
return cache != null;
}
/**
* Runs a callback each time the current Workspace changes.
*/
public void subscribe(Runnable callback) {
synchronized (subscribers) {
subscribers.add(callback);
}
}
/**
* Stops notifications to a callback passed to {@link #subscribe}.
*/
public void unsubscribe(Runnable callback) {
synchronized (subscribers) {
subscribers.remove(callback);
}
}
/**
* The Dart plugin uses this registry key to avoid bazel users getting their settings overridden on projects that include a
* pubspec.yaml.
* <p>
* In other words, this key tells the plugin to configure dart projects without pubspec.yaml.
*/
private static final String dartProjectsWithoutPubspecRegistryKey = "dart.projects.without.pubspec";
/**
* Executes a cache refresh.
*/
private void refresh() {
final Workspace workspace = Workspace.loadUncached(project);
if (workspace == cache && !disconnected) return;
if (cache != null && workspace == null) {
disconnected = true;
return;
}
disconnected = false;
cache = workspace;
// If the current workspace is a bazel workspace, update the Dart plugin
// registry key to indicate that there are dart projects without pubspec
// registry keys. TODO(jacobr): it would be nice if the Dart plugin was
// instead smarter about handling Bazel projects.
if (cache != null) {
if (!Registry.is(dartProjectsWithoutPubspecRegistryKey, false)) {
Registry.get(dartProjectsWithoutPubspecRegistryKey).setValue(true);
}
}
notifyListeners();
}
private Set<Runnable> getSubscribers() {
synchronized (subscribers) {
return ImmutableSet.copyOf(subscribers);
}
}
private void notifyListeners() {
if (project.isDisposed()) {
return;
}
for (Runnable sub : getSubscribers()) {
try {
sub.run();
}
catch (Exception e) {
if (!Objects.equal(e.getMessage(), "expected failure in test")) {
FlutterUtils.warn(LOG, "A subscriber to a WorkspaceCache threw an exception", e);
}
}
}
}
private static final Logger LOG = Logger.getInstance(WorkspaceCache.class);
}
| flutter-intellij/flutter-idea/src/io/flutter/bazel/WorkspaceCache.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/bazel/WorkspaceCache.java",
"repo_id": "flutter-intellij",
"token_count": 1681
} | 492 |
/*
* Copyright 2019 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.
*/
package io.flutter.editor;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.ui.components.JBTextField;
import com.intellij.ui.components.fields.ExtendableTextField;
import io.flutter.inspector.InspectorObjectGroupManager;
import io.flutter.inspector.InspectorService;
import io.flutter.utils.ColorIconMaker;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.dartlang.analysis.server.protocol.FlutterWidgetProperty;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.concurrent.CompletableFuture;
/**
* Field that displays a color property including a clickable color icon that
* opens a color picker.
*/
class ColorField extends ExtendableTextField {
private final String originalExpression;
private final String name;
private final Extension setColorExtension;
@Nullable private Color currentColor;
private ColorPickerProvider colorPicker;
private final PropertyEditorPanel panel;
private Color colorAtPopupLaunch;
private String expressionAtPopupLaunch;
public ColorField(PropertyEditorPanel panel, String name, FlutterWidgetProperty property, Disposable parentDisposable) {
super("", 1);
this.name = name;
final String expression = property.getExpression();
if (expression != null) {
setText(expression);
}
this.originalExpression = expression;
currentColor = parseColorExpression(expression);
final ColorIconMaker maker = new ColorIconMaker();
// InputEvent.SHIFT_DOWN_MASK ?
final KeyStroke keyStroke = KeyStroke.getKeyStroke(10, 64);
setColorExtension =
new Extension() {
@Override
public boolean isIconBeforeText() {
return true;
}
public Icon getIcon(boolean hovered) {
if (currentColor == null) {
return AllIcons.Actions.Colors;
}
return maker.getCustomIcon(currentColor);
}
public String getTooltip() {
return "Edit color";
}
public Runnable getActionOnClick() {
return () -> showColorFieldPopup();
}
};
(new DumbAwareAction() {
public void actionPerformed(@NotNull AnActionEvent e) {
showColorFieldPopup();
}
}).registerCustomShortcutSet(new CustomShortcutSet(keyStroke), this, parentDisposable);
addExtension(setColorExtension);
panel.addTextFieldListeners(name, this);
this.panel = panel;
}
@Nullable
private static Color parseColorExpression(String expression) {
if (expression == null) return null;
final String colorsPrefix = "Colors.";
if (expression.startsWith(colorsPrefix)) {
final FlutterColors.FlutterColor flutterColor = FlutterColors.getColor(expression.substring(colorsPrefix.length()));
if (flutterColor != null) {
return flutterColor.getAWTColor();
}
}
return ExpressionParsingUtils.parseColor(expression);
}
private static String buildColorExpression(@Nullable Color color) {
if (color == null) {
return "";
}
final String flutterColorName = FlutterColors.getColorName(color);
if (flutterColorName != null) {
// TODO(jacobr): only apply this conversion if the material library is already imported in the
// library being edited. We also need to be able to handle cases where the material library is
// imported with a prefix.
return "Colors." + flutterColorName;
}
return String.format(
"Color(0x%02x%02x%02x%02x)", color.getAlpha(), color.getRed(), color.getGreen(), color.getBlue());
}
public void addTextFieldListeners(String name, JBTextField field) {
final FlutterOutline matchingOutline = panel.getCurrentOutline();
field.addActionListener(e -> panel.setPropertyValue(name, field.getText()));
field.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
// The popup is gone if we have received the focus again.
disposeColorPicker();
}
@Override
public void focusLost(FocusEvent e) {
if (panel.getCurrentOutline() != matchingOutline) {
// Don't do anything. The user has moved on to a different outline node.
return;
}
if (e.isTemporary()) {
return;
}
if (colorPicker != null) {
// We lost focus due to the popup being opened so there is no need to
// update the value now. The popup will update the value when it is
// closed.
return;
}
panel.setPropertyValue(name, field.getText());
}
});
}
void cancelPopup() {
currentColor = colorAtPopupLaunch;
setText(expressionAtPopupLaunch);
panel.setPropertyValue(name, originalExpression, true);
repaint();
colorPicker.dispose();
colorPicker = null;
}
void disposeColorPicker() {
if (colorPicker != null) {
colorPicker.dispose();
colorPicker = null;
}
}
void showColorFieldPopup() {
disposeColorPicker();
assert (colorPicker == null);
colorPicker = ColorPickerProvider.EP_NAME.getExtensionList().get(0);
if (colorPicker != null) {
colorAtPopupLaunch = currentColor;
final Insets insets = this.getInsets();
final Point bottomColorIconOffset =
new Point(insets.left + setColorExtension.getIconGap(),
this.getHeight() / 2);
colorPicker
.show(currentColor, this, bottomColorIconOffset, Balloon.Position.atLeft, this::colorListener, this::cancelPopup, this::applyColor);
expressionAtPopupLaunch = getText();
}
}
private void colorListener(@Nullable Color color, Object o) {
if (colorPicker == null) {
// This can happen after a call to cancel.
return;
}
currentColor = color;
final InspectorObjectGroupManager groupManager = panel.getGroupManager();
final String colorExpression = buildColorExpression(color);
// TODO(jacobr): colorField may no longer be the right field in the UI.
setText(colorExpression);
repaint();
if (panel.getNode() != null && groupManager != null) {
// TODO(jacobr): rate limit setting the color property if there is a performance issue.
final InspectorService.ObjectGroup group = groupManager.getCurrent();
final CompletableFuture<Boolean> valueFuture = groupManager.getCurrent().setColorProperty(panel.getNode(), color);
group.safeWhenComplete(valueFuture, (success, error) -> {
if (success == null || error != null) {
return;
}
// TODO(jacobr):
// If setting the property immediately failed, we may have to set the property value fully to see a result.
// This code is risky because it could cause the outline to change and too many hot reloads cause flaky app behavior.
/*
if (!success && color.equals(picker.getColor())) {
setPropertyValue(colorPropertyName, colorExpression);
}*/
});
}
}
private void applyColor() {
disposeColorPicker();
final String colorExpression = buildColorExpression(currentColor);
setText(colorExpression);
panel.setPropertyValue(name, colorExpression);
repaint();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/ColorField.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/ColorField.java",
"repo_id": "flutter-intellij",
"token_count": 2801
} | 493 |
/*
* Copyright 2017 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.
*/
package io.flutter.editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications;
import com.intellij.ui.HyperlinkLabel;
import icons.FlutterIcons;
import io.flutter.FlutterUtils;
import io.flutter.bazel.WorkspaceCache;
import io.flutter.pub.PubRoot;
import io.flutter.sdk.FlutterSdk;
import io.flutter.utils.UIUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public class FlutterPubspecNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware {
private static final Key<EditorNotificationPanel> KEY = Key.create("flutter.pubspec");
public FlutterPubspecNotificationProvider(@NotNull Project project) {
}
@NotNull
@Override
public Key<EditorNotificationPanel> getKey() {
return KEY;
}
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file,
@NotNull FileEditor fileEditor,
@NotNull Project project) {
// We only show this notification inside of local pubspec files.
if (!PubRoot.isPubspec(file) || !file.isInLocalFileSystem()) {
return null;
}
// If the user has opted out of using pub in a project with both bazel rules and pub rules,
// then we will default to bazel instead of pub.
if (WorkspaceCache.getInstance(project).isBazel()) {
return null;
}
// Check that this pubspec file declares flutter
if (!FlutterUtils.declaresFlutter(file)) {
return null;
}
if (FlutterSdk.getFlutterSdk(project) == null) {
return null;
}
return new FlutterPubspecActionsPanel(project, file);
}
static class FlutterPubspecActionsPanel extends EditorNotificationPanel {
@NotNull final Project project;
@NotNull final VirtualFile myFile;
FlutterPubspecActionsPanel(@NotNull Project project, @NotNull VirtualFile file) {
super(UIUtils.getEditorNotificationBackgroundColor());
this.project = project;
myFile = file;
icon(FlutterIcons.Flutter);
text("Flutter commands");
// "flutter.pub.get"
HyperlinkLabel label = createActionLabel("Pub get", () -> runPubGet(false));
label.setToolTipText("Install referenced packages");
// "flutter.pub.upgrade"
label = createActionLabel("Pub upgrade", () -> runPubGet(true));
label.setToolTipText("Upgrade referenced packages to the latest versions");
// If the SDK is the right version, add a 'flutter pub outdated' command.
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk != null && sdk.getVersion().isPubOutdatedSupported()) {
// "flutter.pub.outdated"
label = createActionLabel("Pub outdated", this::runPubOutdated);
label.setToolTipText("Analyze packages to determine which ones can be upgraded");
}
myLinksPanel.add(new JSeparator(SwingConstants.VERTICAL));
label = createActionLabel("Flutter doctor", "flutter.doctor");
label.setToolTipText("Validate installed tools and their versions");
}
private void runPubGet(boolean upgrade) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
return;
}
final PubRoot root = PubRoot.forDirectory(myFile.getParent());
if (root != null) {
if (!upgrade) {
sdk.startPubGet(root, project);
}
else {
sdk.startPubUpgrade(root, project);
}
}
}
private void runPubOutdated() {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
return;
}
final PubRoot root = PubRoot.forDirectory(myFile.getParent());
if (root != null) {
sdk.startPubOutdated(root, project);
}
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterPubspecNotificationProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterPubspecNotificationProvider.java",
"repo_id": "flutter-intellij",
"token_count": 1624
} | 494 |
/*
* Copyright 2019 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.
*/
package io.flutter.editor;
import com.intellij.openapi.editor.Document;
import java.util.Arrays;
import java.util.List;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* Class used to determine whether regular indent guides intersect with
* WidgetIndentGuides.
* <p>
* If indent guides are allowed to render that intersect with widget indent
* guides, there will be flickering or other strange visual artifacts.
* <p>
* It is not possible to get indent guides to render in a stable z-order so
* there is no way to make regular indent guides render before widget indent
* guides. Even if that was possible it would not be desirable as there are
* cases where displaying both guides would be distracting such as showing a
* regular guide at indent 2 that draws a line through the middle of the
* horizontal leg of widget indent guides for a list of children with indent 4.
*/
public class WidgetIndentHitTester {
/**
* Whether each line overlaps a Widget Indent Guide.
*/
private final boolean[] lines;
WidgetIndentHitTester(List<WidgetIndentGuideDescriptor> descriptors, Document document) {
final int lineCount = document.getLineCount();
lines = new boolean[lineCount];
// TODO(jacobr): optimize using a more clever data structure.
for (WidgetIndentGuideDescriptor descriptor : descriptors) {
// if (descriptor.parent)
{
final int last = min(lines.length, descriptor.endLine + 1);
for (int i = max(descriptor.startLine - 1, 0); i < last; i++) {
lines[i] = true;
}
}
}
}
@Override
public int hashCode() {
return Arrays.hashCode(lines);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof WidgetIndentHitTester)) return false;
final WidgetIndentHitTester other = (WidgetIndentHitTester)o;
return Arrays.equals(lines, other.lines);
}
// TODO(jacobr): we could be smarter about intersection detection by
// considering the indent of the intersecting lineRange as well.
// If we could do that we would have to filter out fewer regular indent
// guides that appear to intersect with the widget indent guides.
// This could really be reframed as a rectangle intersection problem but that
// would introduce additional complexity and we have yet to receive feedback
// complaining about the missing regular indent guides for cases where the
// guides overlap horizontally.
public boolean intersects(LineRange lineRange) {
final int last = min(lines.length, lineRange.endLine + 1);
// TODO(jacobr): why the -1 on startLine?
for (int i = max(lineRange.startLine - 1, 0); i < last; i++) {
if (lines[i]) {
return true;
}
}
return false;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentHitTester.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/WidgetIndentHitTester.java",
"repo_id": "flutter-intellij",
"token_count": 896
} | 495 |
/*
* Copyright 2017 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.
*/
package io.flutter.inspector;
/**
* Styles for displaying a node in a [DiagnosticsNode] tree.
* <p>
* Generally these styles are more important for ASCII art rendering than IDE
* rendering with the exception of DiagnosticsTreeStyle.offstage which should
* be used to trigger custom rendering for offstage children perhaps using dashed
* lines or by graying out offstage children.
* <p>
* See also: [DiagnosticsNode.toStringDeep] from https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/foundation/diagnostics.dart
* which dumps text art trees for these styles.
*/
public enum DiagnosticsTreeStyle {
/**
* Render the tree on a single line without showing children acting like the
* line is a header.
*/
headerLine,
/**
* Render the tree without indenting children at all.
*/
flat,
/**
* Style for displaying content describing an error.
*/
error,
/**
* Sparse style for displaying trees.
*/
sparse,
/**
* Connects a node to its parent typically with a dashed line.
*/
offstage,
/**
* Slightly more compact version of the [sparse] style.
* <p>
* Differences between dense and spare are typically only relevant for ASCII
* art display of trees and not for IDE display of trees.
*/
dense,
/**
* Style that enables transitioning from nodes of one style to children of
* another.
* <p>
* Typically doesn't matter for IDE support as all styles are typically
* all styles are compatible as far as IDE display is concerned.
*/
transition,
/**
* Suggestion to render the tree just using whitespace without connecting
* parents to children using lines.
*/
whitespace,
/**
* Render the tree on a single line without showing children.
*/
singleLine,
/**
* Render the tree using a style appropriate for properties that are part of an error message.
* <p>
* The name is placed on one line with the value and properties placed on the following line.
*/
errorProperty,
/**
* Render only the immediate properties of a node instead of the full tree.
* <p>
* As an example, DebugOverflowIndicator uses this style to display just the immediate children
* of a node.
*/
shallow,
/**
* Render only the immediate properties of a node instead of the full tree.
*/
truncateChildren,
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsTreeStyle.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/DiagnosticsTreeStyle.java",
"repo_id": "flutter-intellij",
"token_count": 714
} | 496 |
/*
* Copyright 2019 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.
*/
package io.flutter.inspector;
import java.awt.image.BufferedImage;
public class Screenshot {
public final BufferedImage image;
public final TransformedRect transformedRect;
Screenshot(BufferedImage image, TransformedRect transformedRect) {
this.image = image;
this.transformedRect = transformedRect;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/inspector/Screenshot.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/Screenshot.java",
"repo_id": "flutter-intellij",
"token_count": 141
} | 497 |
/*
* Copyright 2016 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.
*/
package io.flutter.module;
import static java.util.Arrays.asList;
import com.intellij.execution.OutputListener;
import com.intellij.execution.process.ProcessListener;
import com.intellij.ide.projectView.ProjectView;
import com.intellij.ide.projectView.impl.ProjectViewPane;
import com.intellij.ide.util.projectWizard.ModuleBuilder;
import com.intellij.ide.util.projectWizard.ModuleWizardStep;
import com.intellij.ide.util.projectWizard.SettingsStep;
import com.intellij.ide.util.projectWizard.WizardContext;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.module.ModuleType;
import com.intellij.openapi.module.ModuleWithNameAlreadyExists;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModifiableRootModel;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import icons.FlutterIcons;
import io.flutter.FlutterBundle;
import io.flutter.FlutterConstants;
import io.flutter.FlutterMessages;
import io.flutter.FlutterUtils;
import io.flutter.actions.FlutterDoctorAction;
import io.flutter.module.settings.FlutterCreateAdditionalSettingsFields;
import io.flutter.module.settings.SettingsHelpForm;
import io.flutter.pub.PubRoot;
import io.flutter.sdk.FlutterCreateAdditionalSettings;
import io.flutter.sdk.FlutterSdk;
import io.flutter.sdk.FlutterSdkUtil;
import io.flutter.utils.AndroidUtils;
import io.flutter.utils.FlutterModuleUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.concurrent.atomic.AtomicReference;
import javax.swing.ComboBoxEditor;
import javax.swing.Icon;
import javax.swing.JComponent;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterModuleBuilder extends ModuleBuilder {
private static final Logger LOG = Logger.getInstance(FlutterModuleBuilder.class);
protected FlutterModuleWizardStep myStep;
private FlutterCreateAdditionalSettingsFields mySettingsFields;
protected Project myProject;
@Override
public String getName() {
return getPresentableName();
}
@Nullable
public Project getProject() {
return myProject; // Non-null when creating a module.
}
@Override
public String getPresentableName() {
return FlutterBundle.message("flutter.module.name");
}
@Override
public String getDescription() {
return FlutterBundle.message("flutter.project.description");
}
@Override
public Icon getNodeIcon() {
return FlutterIcons.Flutter;
}
@Override
public void setupRootModel(@NotNull ModifiableRootModel model) {
doAddContentEntry(model);
// Add a reference to Dart SDK project library, without committing.
model.addInvalidLibrary("Dart SDK", "project");
}
protected FlutterSdk getFlutterSdk() {
return myStep.getFlutterSdk();
}
@Nullable
@Override
public Module commitModule(@NotNull Project project, @Nullable ModifiableModuleModel model) {
final String basePath = getModuleFileDirectory();
if (basePath == null) {
Messages.showErrorDialog("Module path not set", "Internal Error");
return null;
}
final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(basePath);
if (baseDir == null) {
Messages.showErrorDialog("Unable to determine Flutter project directory", "Internal Error");
return null;
}
final FlutterSdk sdk = getFlutterSdk();
if (sdk == null) {
Messages.showErrorDialog("Flutter SDK not found", "Error");
return null;
}
final OutputListener listener = new OutputListener();
@NotNull final FlutterCreateAdditionalSettings settings = getAdditionalSettings();
settings.setProjectName(super.getName());
final PubRoot root = runFlutterCreateWithProgress(baseDir, sdk, project, listener, settings);
if (root == null) {
final String stderr = listener.getOutput().getStderr();
final String msg = stderr.isEmpty() ? "Flutter create command was unsuccessful" : stderr;
final int code = FlutterMessages.showDialog(project, msg, "Project Creation Error", new String[]{"Run Flutter Doctor", "Cancel"}, 0);
if (code == 0) {
new FlutterDoctorAction().startCommand(project, sdk, null);
}
return null;
}
FlutterSdkUtil.updateKnownSdkPaths(sdk.getHomePath());
// Create the Flutter module. This indirectly calls setupRootModule, etc.
final Module flutter = super.commitModule(project, model);
if (flutter == null) {
return null;
}
FlutterModuleUtils.autoShowMain(project, root);
showProjectInProjectWindow(project);
return flutter;
}
private void showProjectInProjectWindow(@NotNull Project project) {
ApplicationManager.getApplication().invokeLater(() -> {
DumbService.getInstance(project).runWhenSmart(() -> {
ApplicationManager.getApplication().invokeLater(() -> {
ProjectView view = ProjectView.getInstance(project);
if (view == null) return;
view.changeView(ProjectViewPane.ID);
});
});
});
}
private String validateSettings(FlutterCreateAdditionalSettings settings) {
final String description = settings.getDescription();
if (description != null && description.contains(": ")) {
return FlutterBundle.message("npw_invalid_desc_error");
}
final String org = settings.getOrg();
if (org == null) {
return null;
}
if (StringUtils.endsWith(org, ".")) {
return FlutterBundle.message("npw_invalid_org_error");
}
if (mySettingsFields.shouldIncludePlatforms() && !settings.isSomePlatformSelected()) {
return FlutterBundle.message("npw_none_selected_error");
}
// Invalid package names will cause issues down the line.
return AndroidUtils.validateAndroidPackageName(org);
}
public static void addAndroidModule(@NotNull Project project,
@Nullable ModifiableModuleModel model,
@NotNull String baseDirPath,
@NotNull String flutterModuleName,
boolean isTopLevel) {
final VirtualFile baseDir = LocalFileSystem.getInstance().refreshAndFindFileByPath(baseDirPath);
if (baseDir == null) {
return;
}
final VirtualFile androidFile = isTopLevel
? findAndroidModuleFile(baseDir, flutterModuleName)
: findEmbeddedModuleFile(baseDir, flutterModuleName);
if (androidFile == null) return;
addAndroidModuleFromFile(project, model, androidFile);
}
public static void addAndroidModuleFromFile(@NotNull Project project,
@Nullable ModifiableModuleModel model,
@NotNull VirtualFile androidFile) {
try {
final ModifiableModuleModel toCommit;
if (model == null) {
toCommit = ModuleManager.getInstance(project).getModifiableModel();
//noinspection AssignmentToMethodParameter
model = toCommit;
}
else {
toCommit = null;
}
Module newModule = model.loadModule(androidFile.getPath());
if (toCommit != null) {
ApplicationManager.getApplication().invokeLater(() -> {
// This check isn't normally needed but can prevent scary problems during testing.
// Even if .idea is removed modules may still be created from something in the cache files
// if the project had been opened previously.
if (ModuleManager.getInstance(project).findModuleByName(newModule.getName()) == null) {
WriteAction.run(toCommit::commit);
}
});
}
}
catch (ModuleWithNameAlreadyExists | IOException e) {
FlutterUtils.warn(LOG, e);
}
}
@Nullable
private static VirtualFile findAndroidModuleFile(@NotNull VirtualFile baseDir, String flutterModuleName) {
baseDir.refresh(false, false);
for (String name : asList(flutterModuleName + "_android.iml", "android.iml")) {
final VirtualFile candidate = baseDir.findChild(name);
if (candidate != null && candidate.exists()) {
return candidate;
}
}
return null;
}
@Nullable
private static VirtualFile findEmbeddedModuleFile(@NotNull VirtualFile baseDir, String flutterModuleName) {
baseDir.refresh(false, false);
for (String name : asList("android", ".android")) {
VirtualFile dir = baseDir.findChild(name);
if (dir != null && dir.exists()) {
VirtualFile candidate = dir.findChild(flutterModuleName + "_android.iml");
if (candidate != null && candidate.exists()) {
return candidate;
}
}
}
return null;
}
@Override
public boolean validate(@Nullable Project current, @NotNull Project dest) {
final String settingsValidation = validateSettings(getAdditionalSettings());
if (settingsValidation != null) {
Messages.showErrorDialog(settingsValidation, "Error");
try {
Files.deleteIfExists(Path.of(dest.getBasePath()));
}
catch (IOException e) {
// ignore it
}
return false;
}
return myStep.getFlutterSdk() != null;
}
/**
* @see <a href="dart.dev/tools/pub/pubspec#name">https://dart.dev/tools/pub/pubspec#name</a>
*/
@Override
public boolean validateModuleName(@NotNull String moduleName) throws ConfigurationException {
if (!FlutterUtils.isValidPackageName(moduleName)) {
throw new ConfigurationException(
"Invalid module name: '" + moduleName + "' - must be a valid Dart package name (lower_case_with_underscores).");
}
if (FlutterUtils.isDartKeyword(moduleName)) {
throw new ConfigurationException("Invalid module name: '" + moduleName + "' - must not be a Dart keyword.");
}
if (!FlutterUtils.isValidDartIdentifier(moduleName)) {
throw new ConfigurationException("Invalid module name: '" + moduleName + "' - must be a valid Dart identifier.");
}
if (FlutterConstants.FLUTTER_PACKAGE_DEPENDENCIES.contains(moduleName)) {
throw new ConfigurationException(
"Invalid module name: '" + moduleName + "' - this will conflict with Flutter package dependencies.");
}
return super.validateModuleName(moduleName);
}
@NotNull
public FlutterCreateAdditionalSettings getAdditionalSettings() {
return mySettingsFields.getAdditionalSettings();
}
@Nullable
@Override
public ModuleWizardStep modifySettingsStep(@NotNull SettingsStep settingsStep) {
final ModuleWizardStep wizard = super.modifySettingsStep(settingsStep);
mySettingsFields.addSettingsFields(settingsStep);
return wizard;
}
@Override
public ModuleWizardStep modifyProjectTypeStep(@NotNull SettingsStep settingsStep) {
// Don't allow super to add an SDK selection field (#2052).
return null;
}
@Override
public ModuleWizardStep getCustomOptionsStep(final WizardContext context, final Disposable parentDisposable) {
if (!context.isCreatingNewProject()) {
myProject = context.getProject();
}
myStep = new FlutterModuleWizardStep(context);
mySettingsFields = new FlutterCreateAdditionalSettingsFields(new FlutterCreateAdditionalSettings(), this::getFlutterSdk);
Disposer.register(parentDisposable, myStep);
return myStep;
}
@Override
public String getBuilderId() {
// The builder id is used to distinguish between different builders with the same module type, see
// com.intellij.ide.projectWizard.ProjectTypeStep for an example.
return StringUtil.notNullize(super.getBuilderId()) + "_" + FlutterModuleBuilder.class.getCanonicalName();
}
@Override
@NotNull
public ModuleType<?> getModuleType() {
return FlutterModuleUtils.getFlutterModuleType();
}
/**
* Runs flutter create without showing a console, but with an indeterminate progress dialog.
* <p>
* Returns the PubRoot if successful.
*/
@Nullable
public static PubRoot runFlutterCreateWithProgress(@NotNull VirtualFile baseDir,
@NotNull FlutterSdk sdk,
@NotNull Project project,
@Nullable ProcessListener processListener,
@Nullable FlutterCreateAdditionalSettings additionalSettings) {
final ProgressManager progress = ProgressManager.getInstance();
final AtomicReference<PubRoot> result = new AtomicReference<>(null);
FlutterUtils.disableGradleProjectMigrationNotification(project);
progress.runProcessWithProgressSynchronously(() -> {
progress.getProgressIndicator().setIndeterminate(true);
result.set(sdk.createFiles(baseDir, null, processListener, additionalSettings));
}, "Creating Flutter project", false, project);
return result.get();
}
public void setFlutterSdkPath(String s) {
final ComboBoxEditor combo = myStep.myPeer.getSdkEditor();
combo.setItem(s);
}
public FlutterCreateAdditionalSettingsFields getSettingsField() {
return mySettingsFields;
}
public class FlutterModuleWizardStep extends ModuleWizardStep implements Disposable {
private final FlutterGeneratorPeer myPeer;
public FlutterModuleWizardStep(@NotNull WizardContext context) {
//TODO(pq): find a way to listen to wizard cancelation and propagate to peer.
myPeer = new FlutterGeneratorPeer(context);
if (!FlutterUtils.isAndroidStudio()) {
myPeer.getHelpForm().showGettingStarted();
}
}
public SettingsHelpForm getHelpForm() {
return myPeer.getHelpForm();
}
@Override
public JComponent getComponent() {
return myPeer.getComponent();
}
@Override
public void updateDataModel() {
mySettingsFields.updateProjectTypes();
}
@Override
public boolean validate() {
final boolean valid = myPeer.validate();
if (valid) {
myPeer.apply();
}
return valid;
}
@Override
public void dispose() {
}
@Nullable
FlutterSdk getFlutterSdk() {
final String sdkPath = myPeer.getSdkComboPath();
// Ensure the local filesystem has caught up to external processes (e.g., git clone).
if (!sdkPath.isEmpty()) {
try {
LocalFileSystem
.getInstance().refreshAndFindFileByPath(sdkPath);
}
catch (Throwable e) {
// It's possible that the refresh will fail in which case we just want to trap and ignore.
}
}
return FlutterSdk.forPath(sdkPath);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/module/FlutterModuleBuilder.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/FlutterModuleBuilder.java",
"repo_id": "flutter-intellij",
"token_count": 5577
} | 498 |
/*
* Copyright 2018 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.
*/
package io.flutter.perf;
import com.intellij.openapi.util.TextRange;
import org.jetbrains.annotations.Nullable;
/**
* Mapper from a line column offset to a range of text associated with the identifier at an
* offset.
* <p>
* For example, if there is a constructor call at the specified line and offset then the
* name of the constructor called should be returned.
*/
public interface FileLocationMapper {
@Nullable
TextRange getIdentifierRange(int line, int column);
@Nullable
String getText(@Nullable TextRange textRange);
String getPath();
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/FileLocationMapper.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/FileLocationMapper.java",
"repo_id": "flutter-intellij",
"token_count": 205
} | 499 |
/*
* Copyright 2018 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.
*/
package io.flutter.perf;
import org.jetbrains.annotations.NotNull;
/**
* Snapshot of a SlidingWindowStats object for a specific time.
*/
public class SlidingWindowStatsSummary {
private final int[] cachedStats;
private final @NotNull Location location;
public SlidingWindowStatsSummary(@NotNull SlidingWindowStats stats, int currentTime, @NotNull Location location) {
cachedStats = new int[PerfMetric.values().length];
for (PerfMetric metric : PerfMetric.values()) {
cachedStats[metric.ordinal()] = stats.getValue(metric, currentTime);
}
this.location = location;
}
public @NotNull
Location getLocation() {
return location;
}
public int getValue(PerfMetric metric) {
return cachedStats[metric.ordinal()];
}
}
| flutter-intellij/flutter-idea/src/io/flutter/perf/SlidingWindowStatsSummary.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/SlidingWindowStatsSummary.java",
"repo_id": "flutter-intellij",
"token_count": 290
} | 500 |
/*
* Copyright 2018 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.
*/
package io.flutter.preview;
import com.intellij.openapi.util.text.StringUtil;
import org.dartlang.analysis.server.protocol.Element;
import org.dartlang.analysis.server.protocol.FlutterOutline;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class ModelUtils {
private ModelUtils() {
}
public static boolean isBuildMethod(@NotNull Element element) {
if (element.getName() == null || element.getParameters() == null) {
return false;
}
return StringUtil.equals("build", element.getName()) &&
StringUtil.startsWith(element.getParameters(), "(BuildContext ");
}
public static boolean containsBuildMethod(FlutterOutline outline) {
final Element element = outline.getDartElement();
if (element == null) {
return false;
}
if (isBuildMethod(element)) {
return true;
}
final List<FlutterOutline> children = outline.getChildren();
if (children == null) {
return false;
}
for (FlutterOutline child : children) {
if (containsBuildMethod(child)) {
return true;
}
}
return false;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/preview/ModelUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/preview/ModelUtils.java",
"repo_id": "flutter-intellij",
"token_count": 452
} | 501 |
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.flutter.run;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.execution.ui.RunContentDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.run.daemon.DeviceService;
import io.flutter.run.daemon.FlutterApp;
import org.jetbrains.annotations.NotNull;
public class AttachState extends LaunchState {
public AttachState(@NotNull ExecutionEnvironment env,
@NotNull VirtualFile workDir,
@NotNull VirtualFile sourceLocation,
@NotNull RunConfig runConfig,
@NotNull CreateAppCallback createAppCallback) {
super(env, workDir, sourceLocation, runConfig, createAppCallback);
}
@Override
protected RunContentDescriptor launch(@NotNull ExecutionEnvironment env) throws ExecutionException {
final Project project = getEnvironment().getProject();
final FlutterDevice device = DeviceService.getInstance(project).getSelectedDevice();
if (device == null) {
showNoDeviceConnectedMessage(project);
return null;
}
final FlutterApp app = getCreateAppCallback().createApp(device);
// Cache for use in console configuration, and for updating registered extensionRPCs.
FlutterApp.addToEnvironment(env, app);
final ExecutionResult result = setUpConsoleAndActions(app);
return createDebugSession(env, app, result).getRunContentDescriptor();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/AttachState.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/AttachState.java",
"repo_id": "flutter-intellij",
"token_count": 684
} | 502 |
/*
* Copyright 2017 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.
*/
package io.flutter.run;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.PathUtil;
import com.intellij.xdebugger.XDebuggerUtil;
import com.intellij.xdebugger.XSourcePosition;
import com.jetbrains.lang.dart.DartFileType;
import gnu.trove.THashMap;
import gnu.trove.TIntObjectHashMap;
import io.flutter.vmService.DartVmServiceDebugProcess;
import org.dartlang.vm.service.element.Script;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* A specific version of a Dart file, as downloaded from Observatory.
* <p>
* Corresponds to a
* <a href="https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#script">Script</a>
* in the Observatory API. A new version will be generated after a hot reload (with a different script id).
* <p>
* See
*/
class ObservatoryFile {
/**
* Maps an observatory token id to its line and column.
*/
@Nullable
private final TIntObjectHashMap<Position> positionMap;
/**
* User-visible source code downloaded from Observatory.
* <p>
* The LightVirtualFile has no parent directory so its name will be something like /foo.dart.
* Since it has no location, breakpoints can't be set in this file.
* <p>
* This will be null if not requested when the ObservatoryFile was constructed.
*/
@Nullable
private final LightVirtualFile snapshot;
ObservatoryFile(@NotNull Script script, boolean wantSnapshot) {
final @Nullable List<List<Integer>> tokenPosTable = script.getTokenPosTable();
if (tokenPosTable != null) {
positionMap = createPositionMap(tokenPosTable);
}
else {
positionMap = null;
}
snapshot = wantSnapshot ? createSnapshot(script) : null;
}
boolean hasSnapshot() {
return snapshot != null;
}
/**
* Given a token id, returns the source position to display to the user.
* <p>
* If no local file was provided, uses the snapshot if available. (However, in that
* case, breakpoints won't work.)
*/
@Nullable
XSourcePosition createPosition(@Nullable VirtualFile local, int tokenPos) {
final VirtualFile fileToUse = local == null ? snapshot : local;
if (fileToUse == null) return null;
if (positionMap == null) {
return null;
}
final Position pos = positionMap.get(tokenPos);
if (pos == null) {
return XDebuggerUtil.getInstance().createPositionByOffset(fileToUse, 0);
}
return XDebuggerUtil.getInstance().createPosition(fileToUse, pos.line, pos.column);
}
/**
* Unpacks a position token table into a map from position id to Position.
* <p>
* <p>See <a href="https://github.com/dart-lang/vm_service_drivers/blob/master/dart/tool/service.md#scrip">docs</a>.
*/
@NotNull
private static TIntObjectHashMap<Position> createPositionMap(@NotNull final List<List<Integer>> table) {
final TIntObjectHashMap<Position> result = new TIntObjectHashMap<>();
for (List<Integer> line : table) {
// Each line consists of a line number followed by (tokenId, columnNumber) pairs.
// Both lines and columns are one-based.
final Iterator<Integer> items = line.iterator();
// Convert line number from one-based to zero-based.
final int lineNumber = Math.max(0, items.next() - 1);
while (items.hasNext()) {
final int tokenId = items.next();
// Convert column from one-based to zero-based.
final int column = Math.max(0, items.next() - 1);
result.put(tokenId, new Position(lineNumber, column));
}
}
return result;
}
@Nullable
private static LightVirtualFile createSnapshot(@NotNull Script script) {
// LightVirtualFiles have no parent directory, so just use the filename.
final String filename = PathUtil.getFileName(script.getUri());
final String scriptSource = script.getSource();
if (scriptSource == null) {
return null;
}
final LightVirtualFile snapshot = new LightVirtualFile(filename, DartFileType.INSTANCE, scriptSource);
snapshot.setWritable(false);
return snapshot;
}
/**
* A per-isolate cache of Observatory files.
*/
static class Cache {
@NotNull
private final String isolateId;
@NotNull
private final DartVmServiceDebugProcess.ScriptProvider provider;
/**
* A cache containing each file downloaded from Observatory. The key is a script id.
* Each version of a file is stored as a separate entry.
*/
private final Map<String, ObservatoryFile> versions = new THashMap<>();
Cache(@NotNull String isolateId, @NotNull DartVmServiceDebugProcess.ScriptProvider provider) {
this.isolateId = isolateId;
this.provider = provider;
}
/**
* Returns an observatory file, optionally containing a snapshot.
* <p>
* Downloads it if not in the cache.
* <p>
* Returns null if not available.
*/
@Nullable
ObservatoryFile downloadOrGet(@NotNull String scriptId, boolean wantSnapshot) {
final ObservatoryFile cached = this.versions.get(scriptId);
if (cached != null && (cached.hasSnapshot() || !wantSnapshot)) {
return cached;
}
final Script script = provider.downloadScript(isolateId, scriptId);
if (script == null) return null;
final ObservatoryFile downloaded = new ObservatoryFile(script, wantSnapshot);
this.versions.put(scriptId, downloaded);
if (wantSnapshot && !downloaded.hasSnapshot()) {
return null;
}
return downloaded;
}
}
private static class Position {
final int line; // zero-based
final int column; // zero-based
Position(int line, int column) {
this.line = line;
this.column = column;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/ObservatoryFile.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/ObservatoryFile.java",
"repo_id": "flutter-intellij",
"token_count": 2025
} | 503 |
/*
* Copyright 2018 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.
*/
package io.flutter.run.bazelTest;
import com.intellij.execution.ExecutionResult;
import com.intellij.execution.runners.ExecutionEnvironment;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.xdebugger.XDebugSession;
import com.jetbrains.lang.dart.util.DartUrlResolver;
import io.flutter.ObservatoryConnector;
import io.flutter.run.FlutterPopFrameAction;
import io.flutter.run.OpenDevToolsAction;
import io.flutter.vmService.DartVmServiceDebugProcess;
import org.jetbrains.annotations.NotNull;
/**
* The Bazel version of the {@link io.flutter.run.test.TestDebugProcess}.
*/
public class BazelTestDebugProcess extends DartVmServiceDebugProcess {
@NotNull
private final ObservatoryConnector connector;
public BazelTestDebugProcess(@NotNull ExecutionEnvironment executionEnvironment,
@NotNull XDebugSession session,
@NotNull ExecutionResult executionResult,
@NotNull DartUrlResolver dartUrlResolver,
@NotNull ObservatoryConnector connector,
@NotNull PositionMapper mapper) {
super(executionEnvironment, session, executionResult, dartUrlResolver, connector, mapper);
this.connector = connector;
}
@Override
public void registerAdditionalActions(@NotNull DefaultActionGroup leftToolbar,
@NotNull DefaultActionGroup topToolbar,
@NotNull DefaultActionGroup settings) {
topToolbar.addSeparator();
topToolbar.addAction(new FlutterPopFrameAction());
topToolbar.addAction(new OpenDevToolsAction(connector, this::isActive));
}
private boolean isActive() {
return connector.getBrowserUrl() != null && getVmConnected() && !getSession().isStopped();
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestDebugProcess.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/BazelTestDebugProcess.java",
"repo_id": "flutter-intellij",
"token_count": 756
} | 504 |
/*
* Copyright 2021 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.
*/
package io.flutter.run.coverage;
import com.intellij.coverage.CoverageAnnotator;
import com.intellij.coverage.CoverageEngine;
import com.intellij.coverage.CoverageFileProvider;
import com.intellij.coverage.CoverageRunner;
import com.intellij.coverage.CoverageSuite;
import com.intellij.coverage.CoverageSuitesBundle;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.execution.configurations.RunProfile;
import com.intellij.execution.configurations.WrappingRunConfiguration;
import com.intellij.execution.configurations.coverage.CoverageEnabledConfiguration;
import com.intellij.execution.testframework.AbstractTestProxy;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.lang.dart.DartFileType;
import com.jetbrains.lang.dart.psi.DartFile;
import io.flutter.FlutterBundle;
import io.flutter.FlutterUtils;
import io.flutter.pub.PubRoot;
import io.flutter.run.test.TestConfig;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterCoverageEngine extends CoverageEngine {
public static FlutterCoverageEngine getInstance() {
return CoverageEngine.EP_NAME.findExtensionOrFail(FlutterCoverageEngine.class);
}
@Override
public boolean isApplicableTo(@NotNull RunConfigurationBase conf) {
return unwrapRunProfile(conf) instanceof TestConfig;
}
@Override
public boolean canHavePerTestCoverage(@NotNull RunConfigurationBase conf) {
return true;
}
@Override
public @NotNull CoverageEnabledConfiguration createCoverageEnabledConfiguration(@NotNull RunConfigurationBase conf) {
return new FlutterCoverageEnabledConfiguration(conf);
}
@Override
public @Nullable CoverageSuite createCoverageSuite(@NotNull CoverageRunner covRunner,
@NotNull String name,
@NotNull CoverageFileProvider coverageDataFileProvider,
@Nullable String[] filters,
long lastCoverageTimeStamp,
@Nullable String suiteToMerge,
boolean coverageByTestEnabled,
boolean tracingEnabled,
boolean trackTestFolders,
Project project) {
return null;
}
@Override
public @Nullable CoverageSuite createCoverageSuite(@NotNull CoverageRunner covRunner,
@NotNull String name,
@NotNull CoverageFileProvider coverageDataFileProvider,
@NotNull CoverageEnabledConfiguration config) {
if (config instanceof FlutterCoverageEnabledConfiguration) {
return new FlutterCoverageSuite(covRunner, name, coverageDataFileProvider,
config.getConfiguration().getProject(), this);
}
return null;
}
@Override
public @Nullable CoverageSuite createEmptyCoverageSuite(@NotNull CoverageRunner coverageRunner) {
return new FlutterCoverageSuite(this);
}
@Override
public @NotNull CoverageAnnotator getCoverageAnnotator(Project project) {
return FlutterCoverageAnnotator.getInstance(project);
}
@Override
public boolean coverageEditorHighlightingApplicableTo(@NotNull PsiFile psiFile) {
final PubRoot root = PubRoot.forPsiFile(psiFile);
if (root == null) return false;
final VirtualFile file = psiFile.getVirtualFile();
if (file == null) return false;
final String path = root.getRelativePath(file);
if (path == null) return false;
return path.startsWith("lib") && FlutterUtils.isDartFile(file);
}
@Override
public boolean coverageProjectViewStatisticsApplicableTo(VirtualFile fileOrDir) {
return !fileOrDir.isDirectory() && fileOrDir.getFileType() instanceof DartFileType;
}
@Override
public boolean acceptedByFilters(@NotNull PsiFile psiFile, @NotNull CoverageSuitesBundle suite) {
return psiFile instanceof DartFile;
}
@Override
public boolean recompileProjectAndRerunAction(@NotNull Module module,
@NotNull CoverageSuitesBundle suite,
@NotNull Runnable chooseSuiteAction) {
return false;
}
@Override
public String getQualifiedName(@NotNull final File outputFile,
@NotNull final PsiFile sourceFile) {
return getQName(sourceFile);
}
@Override
public @NotNull Set<String> getQualifiedNames(@NotNull PsiFile sourceFile) {
final Set<String> qualifiedNames = new HashSet<>();
qualifiedNames.add(getQName(sourceFile));
return qualifiedNames;
}
@Override
public List<PsiElement> findTestsByNames(@NotNull String[] testNames, @NotNull Project project) {
return null;
}
@Override
public @Nullable String getTestMethodName(@NotNull PsiElement element, @NotNull AbstractTestProxy testProxy) {
return null;
}
@Override
public String getPresentableText() {
return FlutterBundle.message("flutter.coverage.presentable.text");
}
@NotNull
private static String getQName(@NotNull PsiFile sourceFile) {
return sourceFile.getVirtualFile().getPath();
}
static @NotNull RunProfile unwrapRunProfile(@NotNull RunProfile runProfile) {
if (runProfile instanceof WrappingRunConfiguration) {
return ((WrappingRunConfiguration<?>)runProfile).getPeer();
}
return runProfile;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageEngine.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/coverage/FlutterCoverageEngine.java",
"repo_id": "flutter-intellij",
"token_count": 2443
} | 505 |
/*
* Copyright 2017 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.
*/
package io.flutter.run.test;
import com.intellij.execution.configurations.ConfigurationFactory;
import com.intellij.execution.configurations.ConfigurationTypeBase;
import com.intellij.execution.configurations.RunConfiguration;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.project.Project;
import icons.FlutterIcons;
import io.flutter.run.FlutterRunConfigurationType;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
/**
* The type of configs that run tests using "flutter test".
*/
public class FlutterTestConfigType extends ConfigurationTypeBase {
protected FlutterTestConfigType() {
super("FlutterTestConfigType", "Flutter Test", "description", FlutterIcons.Flutter_test);
addFactory(new Factory(this));
}
public static FlutterTestConfigType getInstance() {
return Extensions.findExtension(CONFIGURATION_TYPE_EP, FlutterTestConfigType.class);
}
private static class Factory extends ConfigurationFactory {
public Factory(FlutterTestConfigType type) {
super(type);
}
@NotNull
@Override
@NonNls
public String getId() {
return "Flutter Test";
}
@NotNull
@Override
public RunConfiguration createTemplateConfiguration(@NotNull Project project) {
return new TestConfig(project, this, "Flutter Test");
}
@Override
public boolean isApplicable(@NotNull Project project) {
return FlutterRunConfigurationType.doShowFlutterRunConfigurationForProject(project);
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConfigType.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/FlutterTestConfigType.java",
"repo_id": "flutter-intellij",
"token_count": 528
} | 506 |
/*
* Copyright 2018 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.
*/
package io.flutter.samples;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.ui.EditorNotificationPanel;
import com.intellij.ui.EditorNotifications;
import com.jetbrains.lang.dart.psi.DartClass;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;
public class FlutterSampleNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware {
private static final Key<EditorNotificationPanel> KEY = Key.create("flutter.sample");
@NotNull final Project project;
public FlutterSampleNotificationProvider(@NotNull Project project) {
this.project = project;
}
@NotNull
@Override
public Key<EditorNotificationPanel> getKey() {
return KEY;
}
@Nullable
@Override
public EditorNotificationPanel createNotificationPanel(@NotNull VirtualFile file,
@NotNull FileEditor fileEditor,
@NotNull Project project) {
if (!(fileEditor instanceof TextEditor)) {
return null;
}
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
return null;
}
final String flutterPackagePath = sdk.getHomePath() + "/packages/flutter/lib/src/";
final String filePath = file.getPath();
// Only show for files in the flutter sdk.
if (!filePath.startsWith(flutterPackagePath)) {
return null;
}
final TextEditor textEditor = (TextEditor)fileEditor;
final Editor editor = textEditor.getEditor();
final Document document = editor.getDocument();
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
if (psiFile == null || !psiFile.isValid()) {
return null;
}
// Run the code to query the document in a read action.
final List<FlutterSample> samples = ApplicationManager.getApplication().
runReadAction((Computable<List<FlutterSample>>)() -> {
//noinspection CodeBlock2Expr
return getSamplesFromDoc(flutterPackagePath, document, filePath);
});
return samples.isEmpty() ? null : new FlutterSampleActionsPanel(samples);
}
private List<FlutterSample> getSamplesFromDoc(String flutterPackagePath, Document document, String filePath) {
final List<FlutterSample> samples = new ArrayList<>();
// Find all candidate class definitions.
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
assert (psiFile != null);
final DartClass[] classes = PsiTreeUtil.getChildrenOfType(psiFile, DartClass.class);
if (classes == null) {
return Collections.emptyList();
}
// Get the dartdoc for the classes and use a regex to identify which ones have
// "/// {@tool dartpad ...}".
for (DartClass declaration : classes) {
final String name = declaration.getName();
if (name == null || name.startsWith("_")) {
continue;
}
final List<String> dartdoc = DartDocumentUtils.getDartdocFor(document, declaration);
if (containsDartdocFlutterSample(dartdoc)) {
assert (declaration.getName() != null);
String libraryName = filePath.substring(flutterPackagePath.length());
final int index = libraryName.indexOf('/');
if (index != -1) {
libraryName = libraryName.substring(0, index);
final FlutterSample sample = new FlutterSample(libraryName, declaration.getName());
samples.add(sample);
}
}
}
return samples;
}
// "/// {@tool dartpad ...}"
private static final Pattern DARTPAD_TOOL_PATTERN = Pattern.compile("\\{@tool.*\\sdartpad.*}");
/**
* Return whether the given lines of dartdoc text contain a reference to an embedded dartpad Flutter
* widget sample, eg. <code>"/// {\@tool dartpad ...}"</code>(.
*/
@VisibleForTesting
public static boolean containsDartdocFlutterSample(@NotNull List<String> lines) {
if (lines.isEmpty()) {
return false;
}
for (String line : lines) {
if (DARTPAD_TOOL_PATTERN.matcher(line).find()) {
return true;
}
}
return false;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSampleNotificationProvider.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/samples/FlutterSampleNotificationProvider.java",
"repo_id": "flutter-intellij",
"token_count": 1829
} | 507 |
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="io.flutter.sdk.FlutterSettingsConfigurable">
<grid id="27dc6" binding="mainPanel" layout-manager="GridLayoutManager" row-count="9" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="972" height="864"/>
</constraints>
<properties>
<autoscrolls value="true"/>
</properties>
<border type="none"/>
<children>
<grid id="7bd49" layout-manager="GridLayoutManager" row-count="2" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="2" bottom="1" right="0"/>
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="SDK (current project only)"/>
<children>
<component id="a59e7" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="9" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.flutter.version"/>
</properties>
</component>
<component id="926fd" class="com.intellij.ui.components.JBLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="83a87"/>
<text resource-bundle="io/flutter/FlutterBundle" key="flutter.sdk.path.label"/>
</properties>
</component>
<component id="83a87" class="com.intellij.ui.ComboboxWithBrowseButton" binding="mySdkCombo" custom-create="true">
<constraints>
<grid row="0" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="6278f" class="com.intellij.ui.components.JBLabel" binding="myVersionLabel">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="placeholder for version details"/>
</properties>
</component>
<component id="3285c" class="com.intellij.openapi.ui.FixedSizeButton" binding="myCopyButton">
<constraints>
<grid row="1" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="1" anchor="0" fill="0" indent="1" use-parent-layout="false"/>
</constraints>
<properties>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.sdk.copy.content"/>
</properties>
</component>
</children>
</grid>
<grid id="e885c" layout-manager="GridLayoutManager" row-count="3" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="General"/>
<children>
<component id="6304a" class="javax.swing.JCheckBox" binding="myReportUsageInformationCheckBox">
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.report.google.analytics"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.report.analytics.tooltip"/>
</properties>
</component>
<component id="be19f" class="javax.swing.JCheckBox" binding="myEnableVerboseLoggingCheckBox" default-binding="true">
<constraints>
<grid row="1" column="0" row-span="1" col-span="3" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.enable.verbose.logging"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.enable.verbose.logging.tooltip"/>
</properties>
</component>
<component id="c59f0" class="com.intellij.ui.components.labels.LinkLabel" binding="myPrivacyPolicy">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<horizontalAlignment value="2"/>
<horizontalTextPosition value="2"/>
<text value="www.google.com/policies/privacy" noi18n="true"/>
<toolTipText value="http://www.google.com/policies/privacy/" noi18n="true"/>
</properties>
</component>
<component id="efbd7" class="javax.swing.JCheckBox" binding="myAllowTestsInSourcesRoot">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.allow.tests.in.sources"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.allow.tests.tooltip"/>
</properties>
</component>
</children>
</grid>
<grid id="919ec" layout-manager="GridLayoutManager" row-count="6" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title="App Execution"/>
<children>
<component id="356a" class="javax.swing.JCheckBox" binding="myOpenInspectorOnAppLaunchCheckBox">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.open.inspector.on.launch"/>
</properties>
</component>
<component id="87b06" class="javax.swing.JCheckBox" binding="myHotReloadOnSaveCheckBox">
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.hot.reload.on.save"/>
<toolTipText value="On a "Save All" action, hot reload changes into running Flutter apps."/>
</properties>
</component>
<component id="b1533" class="javax.swing.JCheckBox" binding="myShowStructuredErrors">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Show structured errors for Flutter framework issues"/>
</properties>
</component>
<component id="475be" class="javax.swing.JCheckBox" binding="myEnableBazelHotRestartCheckBox">
<constraints>
<grid row="4" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.enable.bazel.hot.restart"/>
</properties>
</component>
<component id="6cf1f" class="javax.swing.JCheckBox" binding="myIncludeAllStackTraces">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="3" use-parent-layout="false"/>
</constraints>
<properties>
<text value="Include all stack traces"/>
<toolTipText value="If checked, only the first exception will include a stack trace."/>
</properties>
</component>
<component id="85c3d" class="javax.swing.JCheckBox" binding="myEnableLogsPreserveAfterHotReloadOrRestart">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.enable.logs.preserve.during.hot.reload.and.restart"/>
</properties>
</component>
</children>
</grid>
<grid id="32490" layout-manager="GridLayoutManager" row-count="4" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title-resource-bundle="io/flutter/FlutterBundle" title-key="settings.editor"/>
<children>
<component id="70775" class="javax.swing.JCheckBox" binding="myShowBuildMethodGuides">
<constraints>
<grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.show.build.guides"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.show.build.guides.tooltip"/>
</properties>
</component>
<component id="8bd46" class="javax.swing.JCheckBox" binding="myOrganizeImportsOnSaveCheckBox" default-binding="true">
<constraints>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="2" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.organize.imports.on.save"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.organize.imports.tooltip"/>
</properties>
</component>
<component id="92f7c" class="javax.swing.JCheckBox" binding="myShowClosingLabels" default-binding="true">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.show.closing.labels"/>
</properties>
</component>
<grid id="596d1" layout-manager="GridLayoutManager" row-count="1" column-count="4" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="a0dd8" class="javax.swing.JCheckBox" binding="myFormatCodeOnSaveCheckBox" default-binding="true">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.format.code.on.save"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.format.code.tooltip"/>
</properties>
</component>
<component id="2bbb1" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="(For project-specific formatting, use"/>
</properties>
</component>
<component id="4b0d8" class="com.intellij.ui.components.ActionLink" binding="settingsLink" custom-create="true">
<constraints>
<grid row="0" column="2" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
</component>
<component id="d9b3b" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="3" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text value="instead)"/>
</properties>
</component>
</children>
</grid>
</children>
</grid>
<grid id="23e52" layout-manager="GridLayoutManager" row-count="5" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title-resource-bundle="io/flutter/FlutterBundle" title-key="settings.experiments"/>
<children>
<component id="42d6c" class="javax.swing.JLabel">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.try.out.features.still.under.development"/>
</properties>
</component>
<component id="33088" class="javax.swing.JCheckBox" binding="mySyncAndroidLibrariesCheckBox">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.enable.android.gradle.sync"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.enable.androi.gradle.sync.tooltip"/>
</properties>
</component>
<component id="33088" class="javax.swing.JCheckBox" binding="myEnableHotUiCheckBox">
<constraints>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.enable.hot.ui"/>
<toolTipText value="Experimental features to graphically edit Flutter build methods."/>
</properties>
</component>
<component id="e902c" class="javax.swing.JCheckBox" binding="myShowAllRunConfigurationsInContextCheckBox">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.show.all.configs"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.show.all.configs.tooltip"/>
</properties>
</component>
<component id="909bb" class="javax.swing.JCheckBox" binding="myEnableJcefBrowserCheckBox">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="io/flutter/FlutterBundle" key="settings.jcef.browser"/>
<toolTipText resource-bundle="io/flutter/FlutterBundle" key="settings.jcef.browser.tooltip"/>
</properties>
</component>
</children>
</grid>
<grid id="3bf2f" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="7" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="etched" title-resource-bundle="io/flutter/FlutterBundle" title-key="settings.font.packages"/>
<children>
<scrollpane id="4e51e">
<constraints>
<grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<verticalScrollBarPolicy value="22"/>
</properties>
<border type="none"/>
<children>
<component id="d4320" class="javax.swing.JTextArea" binding="myFontPackagesTextArea">
<constraints/>
<properties>
<rows value="3"/>
<toolTipText value="Names of font packages to show icon previews"/>
</properties>
</component>
</children>
</scrollpane>
</children>
</grid>
<grid id="3e8a7" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
<children/>
</grid>
<component id="8fe47" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<font swing-font="CheckBoxMenuItem.acceleratorFont"/>
<text value="Settings below apply to all projects"/>
</properties>
</component>
</children>
</grid>
</form>
| flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSettingsConfigurable.form/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterSettingsConfigurable.form",
"repo_id": "flutter-intellij",
"token_count": 9709
} | 508 |
/*
* Copyright 2017 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.
*/
package io.flutter.utils;
import org.jetbrains.annotations.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectionUtils {
private CollectionUtils() {
}
public static <T> boolean anyMatch(@NotNull T[] in, @NotNull final Predicate<T> predicate) {
return anyMatch(Arrays.stream(in), predicate);
}
public static <T> boolean anyMatch(@NotNull final List<T> in, @NotNull final Predicate<T> predicate) {
return anyMatch(in.stream(), predicate);
}
public static <T> boolean anyMatch(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
return in.anyMatch(predicate);
}
public static <T> List<T> filter(@NotNull T[] in, @NotNull final Predicate<T> predicate) {
return filter(Arrays.stream(in), predicate);
}
public static <T> List<T> filter(@NotNull final List<T> in, @NotNull final Predicate<T> predicate) {
return filter(in.stream(), predicate);
}
public static <T> List<T> filter(@NotNull final Stream<T> in, @NotNull final Predicate<T> predicate) {
return in
.filter(predicate)
.collect(Collectors.toList());
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/CollectionUtils.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/CollectionUtils.java",
"repo_id": "flutter-intellij",
"token_count": 462
} | 509 |
/*
* Copyright 2017 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.
*/
package io.flutter.utils;
import java.util.ArrayList;
import java.util.List;
/**
* A class to process regular text output intermixed with newline-delimited JSON.
* <p>
* JSON lines starting with [{ are never split into multiple lines even if they
* are emitted over the course of multiple calls to appendOutput. Regular lines
* on the other hand are emitted immediately so users do not have to wait for
* debug output.
*/
public class StdoutJsonParser {
private final StringBuilder buffer = new StringBuilder();
private boolean bufferIsJson = false;
private final List<String> lines = new ArrayList<>();
private boolean eatNextEol = false;
private boolean isPotentialWindowsReturn = false;
/**
* Write new output to this [StdoutJsonParser].
*/
public void appendOutput(String string) {
for (int i = 0; i < string.length(); ++i) {
final char c = string.charAt(i);
if (eatNextEol) {
eatNextEol = false;
if (c == '\n') {
continue;
}
if (c == '\r' && !isPotentialWindowsReturn) {
eatNextEol = true;
isPotentialWindowsReturn = true;
continue;
}
}
if (isPotentialWindowsReturn) {
isPotentialWindowsReturn = false;
if (c != '\n') {
flushLine();
}
}
buffer.append(c);
if (!bufferIsJson && buffer.length() == 2 && buffer.charAt(0) == '[' && c == '{') {
bufferIsJson = true;
}
else if (bufferIsJson && c == ']' && possiblyTerminatesJson(buffer, string, i)) {
flushLine();
}
if (c == '\n') {
flushLine();
}
if (c == '\r') {
// Wait and decide whether to flush depending on next character.
isPotentialWindowsReturn = true;
}
}
// Eagerly flush if we are not within JSON so regular log text is written as soon as possible.
if (!bufferIsJson) {
flushLine();
}
else if (buffer.toString().endsWith("}]")) {
eatNextEol = true;
flushLine();
}
}
private boolean possiblyTerminatesJson(StringBuilder output, String input, int inputIndex) {
// This is an approximate approach to look for json message terminations inside of strings -
// where the normally terminating eol gets separated from the json.
if (output.length() < 2 || inputIndex + 1 >= input.length()) {
return false;
}
// Look for '}', ']', and a letter
final char prev = output.charAt(output.length() - 2);
final char current = output.charAt(output.length() - 1);
final char next = input.charAt(inputIndex + 1);
return prev == '}' && current == ']' && Character.isAlphabetic(next);
}
private void flushLine() {
if (!buffer.isEmpty()) {
synchronized (lines) {
lines.add(buffer.toString());
}
buffer.setLength(0);
}
bufferIsJson = false;
}
/**
* Read any lines available from the processed output.
*/
public List<String> getAvailableLines() {
synchronized (lines) {
final List<String> copy = new ArrayList<>(lines);
lines.clear();
return copy;
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/StdoutJsonParser.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/StdoutJsonParser.java",
"repo_id": "flutter-intellij",
"token_count": 1230
} | 510 |
/*
* Copyright 2019 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.
*/
package io.flutter.utils.math;
/**
* This class is ported from the Vector class in the Dart vector_math
* package.
*/
public interface Vector {
double[] getStorage();
}
| flutter-intellij/flutter-idea/src/io/flutter/utils/math/Vector.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/math/Vector.java",
"repo_id": "flutter-intellij",
"token_count": 95
} | 511 |
/*
* Copyright 2018 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.
*/
package io.flutter.view;
import com.intellij.util.EventDispatcher;
import com.intellij.util.xmlb.annotations.Attribute;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
/**
* State for the Flutter view.
*/
public class FlutterViewState {
public static final boolean AUTO_SCROLL_DEFAULT = false;
public static final boolean HIGHLIGHT_NODES_SHOWN_IN_BOTH_TREES_DEFAULT = false;
private final EventDispatcher<ChangeListener> dispatcher = EventDispatcher.create(ChangeListener.class);
@Attribute(value = "splitter-proportion")
public float splitterProportion;
@Attribute(value = "should-auto-scroll")
public boolean shouldAutoScroll = AUTO_SCROLL_DEFAULT;
@Attribute(value = "highlight-nodes-shown-in-both-trees")
public boolean highlightNodesShownInBothTrees = HIGHLIGHT_NODES_SHOWN_IN_BOTH_TREES_DEFAULT;
public FlutterViewState() {
}
public float getSplitterProportion() {
return splitterProportion <= 0.0f ? 0.8f : splitterProportion;
}
public void setSplitterProportion(float value) {
splitterProportion = value;
dispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
public boolean getShouldAutoScroll() {
return shouldAutoScroll;
}
public void setShouldAutoScroll(boolean value) {
shouldAutoScroll = value;
dispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
public void addListener(ChangeListener listener) {
dispatcher.addListener(listener);
}
public void removeListener(ChangeListener listener) {
dispatcher.removeListener(listener);
}
void copyFrom(FlutterViewState other) {
splitterProportion = other.splitterProportion;
}
public void setHighlightNodesShownInBothTrees(Boolean value) {
highlightNodesShownInBothTrees = value;
dispatcher.getMulticaster().stateChanged(new ChangeEvent(this));
}
public boolean getHighlightNodesShownInBothTrees() {
return highlightNodesShownInBothTrees;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewState.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/FlutterViewState.java",
"repo_id": "flutter-intellij",
"token_count": 680
} | 512 |
// Copyright 2000-2018 JetBrains s.r.o.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package io.flutter.vmService;
import com.intellij.xdebugger.breakpoints.XBreakpointHandler;
import com.intellij.xdebugger.breakpoints.XBreakpointProperties;
import com.intellij.xdebugger.breakpoints.XLineBreakpoint;
import com.jetbrains.lang.dart.ide.runner.DartLineBreakpointType;
import gnu.trove.THashMap;
import gnu.trove.THashSet;
import org.dartlang.vm.service.element.Breakpoint;
import org.jetbrains.annotations.NotNull;
import java.util.*;
import static com.intellij.icons.AllIcons.Debugger.Db_invalid_breakpoint;
public class DartVmServiceBreakpointHandler extends XBreakpointHandler<XLineBreakpoint<XBreakpointProperties>> {
private final DartVmServiceDebugProcess myDebugProcess;
private final Set<XLineBreakpoint<XBreakpointProperties>> myXBreakpoints = new THashSet<>();
private final Map<String, IsolateBreakpointInfo> myIsolateInfo = new THashMap<>();
private final Map<String, XLineBreakpoint<XBreakpointProperties>> myVmBreakpointIdToXBreakpointMap = new THashMap<>();
public DartVmServiceBreakpointHandler(@NotNull final DartVmServiceDebugProcess debugProcess) {
super(DartLineBreakpointType.class);
myDebugProcess = debugProcess;
}
@Override
public void registerBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> xBreakpoint) {
myXBreakpoints.add(xBreakpoint);
final VmServiceWrapper vmServiceWrapper = myDebugProcess.getVmServiceWrapper();
if (vmServiceWrapper != null) {
vmServiceWrapper.addBreakpointForIsolates(xBreakpoint, myDebugProcess.getIsolateInfos());
}
}
@Override
public void unregisterBreakpoint(@NotNull final XLineBreakpoint<XBreakpointProperties> xBreakpoint, boolean temporary) {
myXBreakpoints.remove(xBreakpoint);
for (IsolateBreakpointInfo info : myIsolateInfo.values()) {
info.unregisterBreakpoint(xBreakpoint);
}
}
public Set<XLineBreakpoint<XBreakpointProperties>> getXBreakpoints() {
return myXBreakpoints;
}
public void vmBreakpointAdded(@NotNull final XLineBreakpoint<XBreakpointProperties> xBreakpoint,
@NotNull final String isolateId,
@NotNull final Breakpoint vmBreakpoint) {
myVmBreakpointIdToXBreakpointMap.put(vmBreakpoint.getId(), xBreakpoint);
final IsolateBreakpointInfo info = getIsolateInfo(isolateId);
info.vmBreakpointAdded(xBreakpoint, vmBreakpoint);
if (vmBreakpoint.getResolved()) {
breakpointResolved(vmBreakpoint);
}
}
public void temporaryBreakpointAdded(String isolateId, Breakpoint vmBreakpoint) {
getIsolateInfo(isolateId).temporaryVmBreakpointAdded(vmBreakpoint.getId());
}
public void removeTemporaryBreakpoints(String isolateId) {
getIsolateInfo(isolateId).removeTemporaryBreakpoints();
}
public void removeAllVmBreakpoints(@NotNull String isolateId) {
final Set<String> vmBreakpoints = getIsolateInfo(isolateId).removeAllVmBreakpoints();
for (String vmBreakpointId : vmBreakpoints) {
myVmBreakpointIdToXBreakpointMap.remove(vmBreakpointId);
}
}
private IsolateBreakpointInfo getIsolateInfo(String isolateId) {
IsolateBreakpointInfo info = myIsolateInfo.get(isolateId);
if (info == null) {
info = new IsolateBreakpointInfo(isolateId, myDebugProcess);
myIsolateInfo.put(isolateId, info);
}
return info;
}
public void breakpointResolved(@NotNull final Breakpoint vmBreakpoint) {
final XLineBreakpoint<XBreakpointProperties> xBreakpoint = myVmBreakpointIdToXBreakpointMap.get(vmBreakpoint.getId());
// This can be null when the breakpoint has been set by another debugger client.
if (xBreakpoint != null) {
myDebugProcess.getSession().updateBreakpointPresentation(xBreakpoint, null, null);
}
}
public void breakpointFailed(@NotNull final XLineBreakpoint<XBreakpointProperties> xBreakpoint) {
// can this xBreakpoint be resolved for other isolate?
myDebugProcess.getSession().updateBreakpointPresentation(xBreakpoint, Db_invalid_breakpoint, null);
}
public XLineBreakpoint<XBreakpointProperties> getXBreakpoint(@NotNull final Breakpoint vmBreakpoint) {
return myVmBreakpointIdToXBreakpointMap.get(vmBreakpoint.getId());
}
}
class IsolateBreakpointInfo {
private final String myIsolateId;
private final DartVmServiceDebugProcess myDebugProcess;
private final List<String> myTemporaryVmBreakpointIds = new ArrayList<>();
private final Map<XLineBreakpoint<XBreakpointProperties>, Set<String>> myXBreakpointToVmBreakpointIdsMap = new THashMap<>();
IsolateBreakpointInfo(@NotNull String isolateId, @NotNull DartVmServiceDebugProcess debugProcess) {
this.myIsolateId = isolateId;
this.myDebugProcess = debugProcess;
}
public void removeTemporaryBreakpoints() {
for (String breakpointId : myTemporaryVmBreakpointIds) {
myDebugProcess.getVmServiceWrapper().removeBreakpoint(myIsolateId, breakpointId);
}
myTemporaryVmBreakpointIds.clear();
}
public Set<String> removeAllVmBreakpoints() {
if (!myDebugProcess.isIsolateAlive(myIsolateId)) {
return new HashSet<>();
}
final Set<String> allVmBreakpoints = new HashSet<>();
synchronized (myXBreakpointToVmBreakpointIdsMap) {
for (Set<String> bps : myXBreakpointToVmBreakpointIdsMap.values()) {
allVmBreakpoints.addAll(bps);
}
myXBreakpointToVmBreakpointIdsMap.clear();
}
for (String vmBreakpointId : allVmBreakpoints) {
myDebugProcess.getVmServiceWrapper().removeBreakpoint(myIsolateId, vmBreakpointId);
}
return allVmBreakpoints;
}
public void temporaryVmBreakpointAdded(String vmBreakpointId) {
myTemporaryVmBreakpointIds.add(vmBreakpointId);
}
public void vmBreakpointAdded(XLineBreakpoint<XBreakpointProperties> xBreakpoint, Breakpoint vmBreakpoint) {
getVmBreakpoints(xBreakpoint).add(vmBreakpoint.getId());
}
public void unregisterBreakpoint(XLineBreakpoint<XBreakpointProperties> xBreakpoint) {
if (myDebugProcess.isIsolateAlive(myIsolateId)) {
for (String vmBreakpointId : getVmBreakpoints(xBreakpoint)) {
myDebugProcess.getVmServiceWrapper().removeBreakpoint(myIsolateId, vmBreakpointId);
}
}
myXBreakpointToVmBreakpointIdsMap.remove(xBreakpoint);
}
private Set<String> getVmBreakpoints(XLineBreakpoint<XBreakpointProperties> xBreakpoint) {
synchronized (myXBreakpointToVmBreakpointIdsMap) {
return myXBreakpointToVmBreakpointIdsMap.computeIfAbsent(xBreakpoint, k -> new HashSet<>());
}
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/DartVmServiceBreakpointHandler.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/DartVmServiceBreakpointHandler.java",
"repo_id": "flutter-intellij",
"token_count": 2402
} | 513 |
package io.flutter.vmService.frame;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorLocation;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.fileEditor.TextEditorLocation;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.xdebugger.XSourcePosition;
import com.intellij.xdebugger.evaluation.ExpressionInfo;
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator;
import com.intellij.xdebugger.frame.XValue;
import com.jetbrains.lang.dart.psi.*;
import com.jetbrains.lang.dart.util.DartResolveUtil;
import gnu.trove.THashSet;
import io.flutter.vmService.DartVmServiceDebugProcess;
import io.flutter.vmService.VmServiceWrapper;
import org.dartlang.vm.service.consumer.GetObjectConsumer;
import org.dartlang.vm.service.element.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DartVmServiceEvaluator extends XDebuggerEvaluator {
private static final Pattern ERROR_PATTERN = Pattern.compile("Error:.* line \\d+ pos \\d+: (.+)");
@NotNull protected final DartVmServiceDebugProcess myDebugProcess;
public DartVmServiceEvaluator(@NotNull final DartVmServiceDebugProcess debugProcess) {
myDebugProcess = debugProcess;
}
@Override
public void evaluate(@NotNull final String expression,
@NotNull final XEvaluationCallback callback,
@Nullable final XSourcePosition expressionPosition) {
final String isolateId = myDebugProcess.getCurrentIsolateId();
final Project project = myDebugProcess.getSession().getProject();
final FileEditorManager manager = FileEditorManager.getInstance(project);
PsiElement element = null;
PsiFile psiFile = null;
final List<VirtualFile> libraryFiles = new ArrayList<>();
// Turn off pausing on exceptions as it is confusing to mouse over an expression
// and to have that trigger pausing at an exception.
if (myDebugProcess.getVmServiceWrapper() == null) {
callback.errorOccurred("Device disconnected");
return;
}
final VmServiceWrapper vmService = myDebugProcess.getVmServiceWrapper();
if (vmService == null) {
// Not connected to the VM yet.
callback.errorOccurred("No connection to the Dart VM");
return;
}
myDebugProcess.getVmServiceWrapper().setExceptionPauseMode(ExceptionPauseMode.None);
final XEvaluationCallback wrappedCallback = new XEvaluationCallback() {
@Override
public void evaluated(@NotNull XValue result) {
vmService.setExceptionPauseMode(myDebugProcess.getBreakOnExceptionMode());
callback.evaluated(result);
}
@Override
public void errorOccurred(@NotNull String errorMessage) {
vmService.setExceptionPauseMode(myDebugProcess.getBreakOnExceptionMode());
callback.errorOccurred(errorMessage);
}
};
if (expressionPosition != null) {
psiFile = PsiManager.getInstance(project).findFile(expressionPosition.getFile());
if (psiFile != null) {
element = psiFile.findElementAt(expressionPosition.getOffset());
}
}
else {
// TODO(jacobr): we could use the most recently selected Dart file instead
// of using the selected file.
final Editor editor = manager.getSelectedTextEditor();
if (editor instanceof TextEditor) {
final TextEditor textEditor = (TextEditor)editor;
final FileEditorLocation fileEditorLocation = textEditor.getCurrentLocation();
final VirtualFile virtualFile = textEditor.getFile();
if (virtualFile != null) {
psiFile = PsiManager.getInstance(project).findFile(virtualFile);
if (psiFile != null && fileEditorLocation instanceof TextEditorLocation) {
final TextEditorLocation textEditorLocation = (TextEditorLocation)fileEditorLocation;
element = psiFile.findElementAt(textEditor.getEditor().logicalPositionToOffset(textEditorLocation.getPosition()));
}
}
}
}
if (psiFile != null) {
libraryFiles.addAll(DartResolveUtil.findLibrary(psiFile));
}
if (isolateId == null) {
wrappedCallback.errorOccurred("No running isolate.");
return;
}
final DartClass dartClass = element != null ? PsiTreeUtil.getParentOfType(element, DartClass.class) : null;
final String dartClassName = dartClass != null ? dartClass.getName() : null;
vmService.getCachedIsolate(isolateId).whenComplete((isolate, error) -> {
if (error != null) {
wrappedCallback.errorOccurred(error.getMessage());
return;
}
if (isolate == null) {
wrappedCallback.errorOccurred("No running isolate.");
return;
}
final LibraryRef libraryRef = findMatchingLibrary(isolate, libraryFiles);
if (dartClassName != null) {
vmService.getObject(isolateId, libraryRef.getId(), new GetObjectConsumer() {
@Override
public void onError(RPCError error) {
wrappedCallback.errorOccurred(error.getMessage());
}
@Override
public void received(Obj response) {
final Library library = (Library)response;
for (ClassRef classRef : library.getClasses()) {
if (classRef.getName().equals(dartClassName)) {
vmService.evaluateInTargetContext(isolateId, classRef.getId(), expression, wrappedCallback);
return;
}
}
// Class not found so just use the library.
vmService.evaluateInTargetContext(isolateId, libraryRef.getId(), expression, wrappedCallback);
}
@Override
public void received(Sentinel response) {
wrappedCallback.errorOccurred(response.getValueAsString());
}
});
}
else {
myDebugProcess.getVmServiceWrapper().evaluateInTargetContext(isolateId, libraryRef.getId(), expression, wrappedCallback);
}
});
}
private LibraryRef findMatchingLibrary(Isolate isolate, List<VirtualFile> libraryFiles) {
if (libraryFiles != null && !libraryFiles.isEmpty()) {
final Set<String> uris = new THashSet<>();
for (VirtualFile libraryFile : libraryFiles) {
uris.addAll(myDebugProcess.getUrisForFile(libraryFile));
}
for (LibraryRef library : isolate.getLibraries()) {
if (uris.contains(library.getUri())) {
return library;
}
}
}
return isolate.getRootLib();
}
@Nullable
@Override
public ExpressionInfo getExpressionInfoAtOffset(@NotNull final Project project,
@NotNull final Document document,
final int offset,
final boolean sideEffectsAllowed) {
final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(document);
final PsiElement contextElement = psiFile == null ? null : psiFile.findElementAt(offset);
return contextElement == null ? null : getExpressionInfo(contextElement);
}
@NotNull
public static String getPresentableError(@NotNull final String rawError) {
//Error: Unhandled exception:
//No top-level getter 'foo' declared.
//
//NoSuchMethodError: method not found: 'foo'
//Receiver: top-level
//Arguments: [...]
//#0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:176)
//#1 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:260)
//#2 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:142)
//Error: '': error: line 1 pos 9: receiver 'this' is not in scope
//() => 1+this.foo();
// ^
final List<String> lines = StringUtil.split(StringUtil.convertLineSeparators(rawError), "\n");
if (!lines.isEmpty()) {
if ((lines.get(0).equals("Error: Unhandled exception:") || lines.get(0).equals("Unhandled exception:")) && lines.size() > 1) {
return lines.get(1);
}
final Matcher matcher = ERROR_PATTERN.matcher(lines.get(0));
if (matcher.find()) {
return matcher.group(1);
}
}
return "Cannot evaluate";
}
@Nullable
public static ExpressionInfo getExpressionInfo(@NotNull final PsiElement contextElement) {
// todo if sideEffectsAllowed return method call like "foo()", not only "foo"
/* WEB-11715
dart psi: notes.text
REFERENCE_EXPRESSION
REFERENCE_EXPRESSION "notes"
PsiElement(.) "."
REFERENCE_EXPRESSION "text"
*/
// find topmost reference, but stop if argument list found
DartReference reference = null;
PsiElement element = contextElement;
while (true) {
if (element instanceof DartReference) {
reference = (DartReference)element;
}
element = element.getParent();
if (element == null ||
// int.parse(slider.value) - we must return reference expression "slider.value", but not the whole expression
element instanceof DartArgumentList ||
// "${seeds} seeds" - we must return only "seeds"
element instanceof DartLongTemplateEntry ||
element instanceof DartCallExpression ||
element instanceof DartFunctionBody || element instanceof IDartBlock) {
break;
}
}
if (reference != null) {
TextRange textRange = reference.getTextRange();
// note<CURSOR>s.text - the whole reference expression is notes.txt, but we must return only notes
final int endOffset = contextElement.getTextRange().getEndOffset();
if (textRange.getEndOffset() != endOffset) {
textRange = new TextRange(textRange.getStartOffset(), endOffset);
}
return new ExpressionInfo(textRange);
}
final PsiElement parent = contextElement.getParent();
return parent instanceof DartId ? new ExpressionInfo(parent.getTextRange()) : null;
}
}
| flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceEvaluator.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/frame/DartVmServiceEvaluator.java",
"repo_id": "flutter-intellij",
"token_count": 3962
} | 514 |
/*
* Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*
* This file has been automatically generated. Please do not edit it manually.
* To regenerate the file, use the script "pkg/analysis_server/tool/spec/generate_files".
*/
package org.dartlang.analysis.server.protocol;
import com.google.common.collect.Lists;
import com.google.dart.server.utilities.general.ObjectUtilities;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* An item of an enumeration in a general sense - actual enum value, or a static field in a class.
*
* @coverage dart.server.generated.types
*/
@SuppressWarnings("unused")
public class FlutterWidgetPropertyValueEnumItem {
public static final FlutterWidgetPropertyValueEnumItem[] EMPTY_ARRAY = new FlutterWidgetPropertyValueEnumItem[0];
public static final List<FlutterWidgetPropertyValueEnumItem> EMPTY_LIST = Lists.newArrayList();
/**
* The URI of the library containing the className. When the enum item is passed back, this will
* allow the server to import the corresponding library if necessary.
*/
private final String libraryUri;
/**
* The name of the class or enum.
*/
private final String className;
/**
* The name of the field in the enumeration, or the static field in the class.
*/
private final String name;
/**
* The documentation to show to the user. Omitted if the server does not know the documentation,
* e.g. because the corresponding field is not documented.
*/
private final String documentation;
/**
* Constructor for {@link FlutterWidgetPropertyValueEnumItem}.
*/
public FlutterWidgetPropertyValueEnumItem(String libraryUri, String className, String name, String documentation) {
this.libraryUri = libraryUri;
this.className = className;
this.name = name;
this.documentation = documentation;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof FlutterWidgetPropertyValueEnumItem) {
FlutterWidgetPropertyValueEnumItem other = (FlutterWidgetPropertyValueEnumItem)obj;
return
ObjectUtilities.equals(other.libraryUri, libraryUri) &&
ObjectUtilities.equals(other.className, className) &&
ObjectUtilities.equals(other.name, name) &&
ObjectUtilities.equals(other.documentation, documentation);
}
return false;
}
public static FlutterWidgetPropertyValueEnumItem fromJson(JsonObject jsonObject) {
String libraryUri = jsonObject.get("libraryUri").getAsString();
String className = jsonObject.get("className").getAsString();
String name = jsonObject.get("name").getAsString();
String documentation = jsonObject.get("documentation") == null ? null : jsonObject.get("documentation").getAsString();
return new FlutterWidgetPropertyValueEnumItem(libraryUri, className, name, documentation);
}
public static List<FlutterWidgetPropertyValueEnumItem> fromJsonArray(JsonArray jsonArray) {
if (jsonArray == null) {
return EMPTY_LIST;
}
ArrayList<FlutterWidgetPropertyValueEnumItem> list = new ArrayList<FlutterWidgetPropertyValueEnumItem>(jsonArray.size());
Iterator<JsonElement> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
list.add(fromJson(iterator.next().getAsJsonObject()));
}
return list;
}
/**
* The name of the class or enum.
*/
public String getClassName() {
return className;
}
/**
* The documentation to show to the user. Omitted if the server does not know the documentation,
* e.g. because the corresponding field is not documented.
*/
public String getDocumentation() {
return documentation;
}
/**
* The URI of the library containing the className. When the enum item is passed back, this will
* allow the server to import the corresponding library if necessary.
*/
public String getLibraryUri() {
return libraryUri;
}
/**
* The name of the field in the enumeration, or the static field in the class.
*/
public String getName() {
return name;
}
@Override
public int hashCode() {
HashCodeBuilder builder = new HashCodeBuilder();
builder.append(libraryUri);
builder.append(className);
builder.append(name);
builder.append(documentation);
return builder.toHashCode();
}
public JsonObject toJson() {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("libraryUri", libraryUri);
jsonObject.addProperty("className", className);
jsonObject.addProperty("name", name);
if (documentation != null) {
jsonObject.addProperty("documentation", documentation);
}
return jsonObject;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[");
builder.append("libraryUri=");
builder.append(libraryUri).append(", ");
builder.append("className=");
builder.append(className).append(", ");
builder.append("name=");
builder.append(name).append(", ");
builder.append("documentation=");
builder.append(documentation);
builder.append("]");
return builder.toString();
}
}
| flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyValueEnumItem.java/0 | {
"file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterWidgetPropertyValueEnumItem.java",
"repo_id": "flutter-intellij",
"token_count": 1706
} | 515 |
# Generated file - do not edit.
# suppress inspection "UnusedProperty" for whole file
f489.codepoint=add
add=cupertino/add.png
f48a.codepoint=add_circled
add_circled=cupertino/add_circled.png
f48b.codepoint=add_circled_solid
add_circled_solid=cupertino/add_circled_solid.png
f4d4.codepoint=airplane
airplane=cupertino/airplane.png
f4d5.codepoint=alarm
alarm=cupertino/alarm.png
f4d6.codepoint=alarm_fill
alarm_fill=cupertino/alarm_fill.png
f4d7.codepoint=alt
alt=cupertino/alt.png
f4d8.codepoint=ant
ant=cupertino/ant.png
f4d9.codepoint=ant_circle
ant_circle=cupertino/ant_circle.png
f4da.codepoint=ant_circle_fill
ant_circle_fill=cupertino/ant_circle_fill.png
f4db.codepoint=ant_fill
ant_fill=cupertino/ant_fill.png
f4dc.codepoint=antenna_radiowaves_left_right
antenna_radiowaves_left_right=cupertino/antenna_radiowaves_left_right.png
f4dd.codepoint=app
app=cupertino/app.png
f4de.codepoint=app_badge
app_badge=cupertino/app_badge.png
f4df.codepoint=app_badge_fill
app_badge_fill=cupertino/app_badge_fill.png
f4e0.codepoint=app_fill
app_fill=cupertino/app_fill.png
f4e1.codepoint=archivebox
archivebox=cupertino/archivebox.png
f4e2.codepoint=archivebox_fill
archivebox_fill=cupertino/archivebox_fill.png
f4e3.codepoint=arrow_2_circlepath
arrow_2_circlepath=cupertino/arrow_2_circlepath.png
f4e4.codepoint=arrow_2_circlepath_circle
arrow_2_circlepath_circle=cupertino/arrow_2_circlepath_circle.png
f4e5.codepoint=arrow_2_circlepath_circle_fill
arrow_2_circlepath_circle_fill=cupertino/arrow_2_circlepath_circle_fill.png
f4e6.codepoint=arrow_2_squarepath
arrow_2_squarepath=cupertino/arrow_2_squarepath.png
f4e7.codepoint=arrow_3_trianglepath
arrow_3_trianglepath=cupertino/arrow_3_trianglepath.png
f4e8.codepoint=arrow_branch
arrow_branch=cupertino/arrow_branch.png
f49a.codepoint=arrow_clockwise
arrow_clockwise=cupertino/arrow_clockwise.png
f49b.codepoint=arrow_clockwise_circle
arrow_clockwise_circle=cupertino/arrow_clockwise_circle.png
f49c.codepoint=arrow_clockwise_circle_fill
arrow_clockwise_circle_fill=cupertino/arrow_clockwise_circle_fill.png
f21c.codepoint=arrow_counterclockwise
arrow_counterclockwise=cupertino/arrow_counterclockwise.png
f4e9.codepoint=arrow_counterclockwise_circle
arrow_counterclockwise_circle=cupertino/arrow_counterclockwise_circle.png
f4ea.codepoint=arrow_counterclockwise_circle_fill
arrow_counterclockwise_circle_fill=cupertino/arrow_counterclockwise_circle_fill.png
f35d.codepoint=arrow_down
arrow_down=cupertino/arrow_down.png
f4eb.codepoint=arrow_down_circle
arrow_down_circle=cupertino/arrow_down_circle.png
f4ec.codepoint=arrow_down_circle_fill
arrow_down_circle_fill=cupertino/arrow_down_circle_fill.png
f4ed.codepoint=arrow_down_doc
arrow_down_doc=cupertino/arrow_down_doc.png
f4ee.codepoint=arrow_down_doc_fill
arrow_down_doc_fill=cupertino/arrow_down_doc_fill.png
f4ef.codepoint=arrow_down_left
arrow_down_left=cupertino/arrow_down_left.png
f4f0.codepoint=arrow_down_left_circle
arrow_down_left_circle=cupertino/arrow_down_left_circle.png
f4f1.codepoint=arrow_down_left_circle_fill
arrow_down_left_circle_fill=cupertino/arrow_down_left_circle_fill.png
f4f2.codepoint=arrow_down_left_square
arrow_down_left_square=cupertino/arrow_down_left_square.png
f4f3.codepoint=arrow_down_left_square_fill
arrow_down_left_square_fill=cupertino/arrow_down_left_square_fill.png
f4f4.codepoint=arrow_down_right
arrow_down_right=cupertino/arrow_down_right.png
f37d.codepoint=arrow_down_right_arrow_up_left
arrow_down_right_arrow_up_left=cupertino/arrow_down_right_arrow_up_left.png
f4f5.codepoint=arrow_down_right_circle
arrow_down_right_circle=cupertino/arrow_down_right_circle.png
f4f6.codepoint=arrow_down_right_circle_fill
arrow_down_right_circle_fill=cupertino/arrow_down_right_circle_fill.png
f4f7.codepoint=arrow_down_right_square
arrow_down_right_square=cupertino/arrow_down_right_square.png
f4f8.codepoint=arrow_down_right_square_fill
arrow_down_right_square_fill=cupertino/arrow_down_right_square_fill.png
f4f9.codepoint=arrow_down_square
arrow_down_square=cupertino/arrow_down_square.png
f4fa.codepoint=arrow_down_square_fill
arrow_down_square_fill=cupertino/arrow_down_square_fill.png
f4fb.codepoint=arrow_down_to_line
arrow_down_to_line=cupertino/arrow_down_to_line.png
f4fc.codepoint=arrow_down_to_line_alt
arrow_down_to_line_alt=cupertino/arrow_down_to_line_alt.png
f4fd.codepoint=arrow_left
arrow_left=cupertino/arrow_left.png
f4fe.codepoint=arrow_left_circle
arrow_left_circle=cupertino/arrow_left_circle.png
f4ff.codepoint=arrow_left_circle_fill
arrow_left_circle_fill=cupertino/arrow_left_circle_fill.png
f500.codepoint=arrow_left_right
arrow_left_right=cupertino/arrow_left_right.png
f501.codepoint=arrow_left_right_circle
arrow_left_right_circle=cupertino/arrow_left_right_circle.png
f502.codepoint=arrow_left_right_circle_fill
arrow_left_right_circle_fill=cupertino/arrow_left_right_circle_fill.png
f503.codepoint=arrow_left_right_square
arrow_left_right_square=cupertino/arrow_left_right_square.png
f504.codepoint=arrow_left_right_square_fill
arrow_left_right_square_fill=cupertino/arrow_left_right_square_fill.png
f505.codepoint=arrow_left_square
arrow_left_square=cupertino/arrow_left_square.png
f506.codepoint=arrow_left_square_fill
arrow_left_square_fill=cupertino/arrow_left_square_fill.png
f507.codepoint=arrow_left_to_line
arrow_left_to_line=cupertino/arrow_left_to_line.png
f508.codepoint=arrow_left_to_line_alt
arrow_left_to_line_alt=cupertino/arrow_left_to_line_alt.png
f509.codepoint=arrow_merge
arrow_merge=cupertino/arrow_merge.png
f50a.codepoint=arrow_right
arrow_right=cupertino/arrow_right.png
f50b.codepoint=arrow_right_arrow_left
arrow_right_arrow_left=cupertino/arrow_right_arrow_left.png
f50c.codepoint=arrow_right_arrow_left_circle
arrow_right_arrow_left_circle=cupertino/arrow_right_arrow_left_circle.png
f50d.codepoint=arrow_right_arrow_left_circle_fill
arrow_right_arrow_left_circle_fill=cupertino/arrow_right_arrow_left_circle_fill.png
f50e.codepoint=arrow_right_arrow_left_square
arrow_right_arrow_left_square=cupertino/arrow_right_arrow_left_square.png
f50f.codepoint=arrow_right_arrow_left_square_fill
arrow_right_arrow_left_square_fill=cupertino/arrow_right_arrow_left_square_fill.png
f510.codepoint=arrow_right_circle
arrow_right_circle=cupertino/arrow_right_circle.png
f511.codepoint=arrow_right_circle_fill
arrow_right_circle_fill=cupertino/arrow_right_circle_fill.png
f512.codepoint=arrow_right_square
arrow_right_square=cupertino/arrow_right_square.png
f513.codepoint=arrow_right_square_fill
arrow_right_square_fill=cupertino/arrow_right_square_fill.png
f514.codepoint=arrow_right_to_line
arrow_right_to_line=cupertino/arrow_right_to_line.png
f515.codepoint=arrow_right_to_line_alt
arrow_right_to_line_alt=cupertino/arrow_right_to_line_alt.png
f516.codepoint=arrow_swap
arrow_swap=cupertino/arrow_swap.png
f517.codepoint=arrow_turn_down_left
arrow_turn_down_left=cupertino/arrow_turn_down_left.png
f518.codepoint=arrow_turn_down_right
arrow_turn_down_right=cupertino/arrow_turn_down_right.png
f519.codepoint=arrow_turn_left_down
arrow_turn_left_down=cupertino/arrow_turn_left_down.png
f51a.codepoint=arrow_turn_left_up
arrow_turn_left_up=cupertino/arrow_turn_left_up.png
f51b.codepoint=arrow_turn_right_down
arrow_turn_right_down=cupertino/arrow_turn_right_down.png
f51c.codepoint=arrow_turn_right_up
arrow_turn_right_up=cupertino/arrow_turn_right_up.png
f51d.codepoint=arrow_turn_up_left
arrow_turn_up_left=cupertino/arrow_turn_up_left.png
f51e.codepoint=arrow_turn_up_right
arrow_turn_up_right=cupertino/arrow_turn_up_right.png
f366.codepoint=arrow_up
arrow_up=cupertino/arrow_up.png
f51f.codepoint=arrow_up_arrow_down
arrow_up_arrow_down=cupertino/arrow_up_arrow_down.png
f520.codepoint=arrow_up_arrow_down_circle
arrow_up_arrow_down_circle=cupertino/arrow_up_arrow_down_circle.png
f521.codepoint=arrow_up_arrow_down_circle_fill
arrow_up_arrow_down_circle_fill=cupertino/arrow_up_arrow_down_circle_fill.png
f522.codepoint=arrow_up_arrow_down_square
arrow_up_arrow_down_square=cupertino/arrow_up_arrow_down_square.png
f523.codepoint=arrow_up_arrow_down_square_fill
arrow_up_arrow_down_square_fill=cupertino/arrow_up_arrow_down_square_fill.png
f524.codepoint=arrow_up_bin
arrow_up_bin=cupertino/arrow_up_bin.png
f525.codepoint=arrow_up_bin_fill
arrow_up_bin_fill=cupertino/arrow_up_bin_fill.png
f526.codepoint=arrow_up_circle
arrow_up_circle=cupertino/arrow_up_circle.png
f527.codepoint=arrow_up_circle_fill
arrow_up_circle_fill=cupertino/arrow_up_circle_fill.png
f528.codepoint=arrow_up_doc
arrow_up_doc=cupertino/arrow_up_doc.png
f529.codepoint=arrow_up_doc_fill
arrow_up_doc_fill=cupertino/arrow_up_doc_fill.png
f52a.codepoint=arrow_up_down
arrow_up_down=cupertino/arrow_up_down.png
f52b.codepoint=arrow_up_down_circle
arrow_up_down_circle=cupertino/arrow_up_down_circle.png
f52c.codepoint=arrow_up_down_circle_fill
arrow_up_down_circle_fill=cupertino/arrow_up_down_circle_fill.png
f52d.codepoint=arrow_up_down_square
arrow_up_down_square=cupertino/arrow_up_down_square.png
f52e.codepoint=arrow_up_down_square_fill
arrow_up_down_square_fill=cupertino/arrow_up_down_square_fill.png
f52f.codepoint=arrow_up_left
arrow_up_left=cupertino/arrow_up_left.png
f386.codepoint=arrow_up_left_arrow_down_right
arrow_up_left_arrow_down_right=cupertino/arrow_up_left_arrow_down_right.png
f530.codepoint=arrow_up_left_circle
arrow_up_left_circle=cupertino/arrow_up_left_circle.png
f531.codepoint=arrow_up_left_circle_fill
arrow_up_left_circle_fill=cupertino/arrow_up_left_circle_fill.png
f532.codepoint=arrow_up_left_square
arrow_up_left_square=cupertino/arrow_up_left_square.png
f533.codepoint=arrow_up_left_square_fill
arrow_up_left_square_fill=cupertino/arrow_up_left_square_fill.png
f534.codepoint=arrow_up_right
arrow_up_right=cupertino/arrow_up_right.png
f535.codepoint=arrow_up_right_circle
arrow_up_right_circle=cupertino/arrow_up_right_circle.png
f536.codepoint=arrow_up_right_circle_fill
arrow_up_right_circle_fill=cupertino/arrow_up_right_circle_fill.png
f537.codepoint=arrow_up_right_diamond
arrow_up_right_diamond=cupertino/arrow_up_right_diamond.png
f538.codepoint=arrow_up_right_diamond_fill
arrow_up_right_diamond_fill=cupertino/arrow_up_right_diamond_fill.png
f539.codepoint=arrow_up_right_square
arrow_up_right_square=cupertino/arrow_up_right_square.png
f53a.codepoint=arrow_up_right_square_fill
arrow_up_right_square_fill=cupertino/arrow_up_right_square_fill.png
f53b.codepoint=arrow_up_square
arrow_up_square=cupertino/arrow_up_square.png
f53c.codepoint=arrow_up_square_fill
arrow_up_square_fill=cupertino/arrow_up_square_fill.png
f53d.codepoint=arrow_up_to_line
arrow_up_to_line=cupertino/arrow_up_to_line.png
f53e.codepoint=arrow_up_to_line_alt
arrow_up_to_line_alt=cupertino/arrow_up_to_line_alt.png
f53f.codepoint=arrow_uturn_down
arrow_uturn_down=cupertino/arrow_uturn_down.png
f540.codepoint=arrow_uturn_down_circle
arrow_uturn_down_circle=cupertino/arrow_uturn_down_circle.png
f541.codepoint=arrow_uturn_down_circle_fill
arrow_uturn_down_circle_fill=cupertino/arrow_uturn_down_circle_fill.png
f542.codepoint=arrow_uturn_down_square
arrow_uturn_down_square=cupertino/arrow_uturn_down_square.png
f543.codepoint=arrow_uturn_down_square_fill
arrow_uturn_down_square_fill=cupertino/arrow_uturn_down_square_fill.png
f544.codepoint=arrow_uturn_left
arrow_uturn_left=cupertino/arrow_uturn_left.png
f545.codepoint=arrow_uturn_left_circle
arrow_uturn_left_circle=cupertino/arrow_uturn_left_circle.png
f546.codepoint=arrow_uturn_left_circle_fill
arrow_uturn_left_circle_fill=cupertino/arrow_uturn_left_circle_fill.png
f547.codepoint=arrow_uturn_left_square
arrow_uturn_left_square=cupertino/arrow_uturn_left_square.png
f548.codepoint=arrow_uturn_left_square_fill
arrow_uturn_left_square_fill=cupertino/arrow_uturn_left_square_fill.png
f549.codepoint=arrow_uturn_right
arrow_uturn_right=cupertino/arrow_uturn_right.png
f54a.codepoint=arrow_uturn_right_circle
arrow_uturn_right_circle=cupertino/arrow_uturn_right_circle.png
f54b.codepoint=arrow_uturn_right_circle_fill
arrow_uturn_right_circle_fill=cupertino/arrow_uturn_right_circle_fill.png
f54c.codepoint=arrow_uturn_right_square
arrow_uturn_right_square=cupertino/arrow_uturn_right_square.png
f54d.codepoint=arrow_uturn_right_square_fill
arrow_uturn_right_square_fill=cupertino/arrow_uturn_right_square_fill.png
f54e.codepoint=arrow_uturn_up
arrow_uturn_up=cupertino/arrow_uturn_up.png
f54f.codepoint=arrow_uturn_up_circle
arrow_uturn_up_circle=cupertino/arrow_uturn_up_circle.png
f550.codepoint=arrow_uturn_up_circle_fill
arrow_uturn_up_circle_fill=cupertino/arrow_uturn_up_circle_fill.png
f551.codepoint=arrow_uturn_up_square
arrow_uturn_up_square=cupertino/arrow_uturn_up_square.png
f552.codepoint=arrow_uturn_up_square_fill
arrow_uturn_up_square_fill=cupertino/arrow_uturn_up_square_fill.png
f4c6.codepoint=arrowshape_turn_up_left
arrowshape_turn_up_left=cupertino/arrowshape_turn_up_left.png
f21d.codepoint=arrowshape_turn_up_left_2
arrowshape_turn_up_left_2=cupertino/arrowshape_turn_up_left_2.png
f21e.codepoint=arrowshape_turn_up_left_2_fill
arrowshape_turn_up_left_2_fill=cupertino/arrowshape_turn_up_left_2_fill.png
f553.codepoint=arrowshape_turn_up_left_circle
arrowshape_turn_up_left_circle=cupertino/arrowshape_turn_up_left_circle.png
f554.codepoint=arrowshape_turn_up_left_circle_fill
arrowshape_turn_up_left_circle_fill=cupertino/arrowshape_turn_up_left_circle_fill.png
f555.codepoint=arrowshape_turn_up_left_fill
arrowshape_turn_up_left_fill=cupertino/arrowshape_turn_up_left_fill.png
f556.codepoint=arrowshape_turn_up_right
arrowshape_turn_up_right=cupertino/arrowshape_turn_up_right.png
f557.codepoint=arrowshape_turn_up_right_circle
arrowshape_turn_up_right_circle=cupertino/arrowshape_turn_up_right_circle.png
f558.codepoint=arrowshape_turn_up_right_circle_fill
arrowshape_turn_up_right_circle_fill=cupertino/arrowshape_turn_up_right_circle_fill.png
f559.codepoint=arrowshape_turn_up_right_fill
arrowshape_turn_up_right_fill=cupertino/arrowshape_turn_up_right_fill.png
f55a.codepoint=arrowtriangle_down
arrowtriangle_down=cupertino/arrowtriangle_down.png
f55b.codepoint=arrowtriangle_down_circle
arrowtriangle_down_circle=cupertino/arrowtriangle_down_circle.png
f55c.codepoint=arrowtriangle_down_circle_fill
arrowtriangle_down_circle_fill=cupertino/arrowtriangle_down_circle_fill.png
f55d.codepoint=arrowtriangle_down_fill
arrowtriangle_down_fill=cupertino/arrowtriangle_down_fill.png
f55e.codepoint=arrowtriangle_down_square
arrowtriangle_down_square=cupertino/arrowtriangle_down_square.png
f55f.codepoint=arrowtriangle_down_square_fill
arrowtriangle_down_square_fill=cupertino/arrowtriangle_down_square_fill.png
f560.codepoint=arrowtriangle_left
arrowtriangle_left=cupertino/arrowtriangle_left.png
f561.codepoint=arrowtriangle_left_circle
arrowtriangle_left_circle=cupertino/arrowtriangle_left_circle.png
f562.codepoint=arrowtriangle_left_circle_fill
arrowtriangle_left_circle_fill=cupertino/arrowtriangle_left_circle_fill.png
f563.codepoint=arrowtriangle_left_fill
arrowtriangle_left_fill=cupertino/arrowtriangle_left_fill.png
f564.codepoint=arrowtriangle_left_square
arrowtriangle_left_square=cupertino/arrowtriangle_left_square.png
f565.codepoint=arrowtriangle_left_square_fill
arrowtriangle_left_square_fill=cupertino/arrowtriangle_left_square_fill.png
f566.codepoint=arrowtriangle_right
arrowtriangle_right=cupertino/arrowtriangle_right.png
f567.codepoint=arrowtriangle_right_circle
arrowtriangle_right_circle=cupertino/arrowtriangle_right_circle.png
f568.codepoint=arrowtriangle_right_circle_fill
arrowtriangle_right_circle_fill=cupertino/arrowtriangle_right_circle_fill.png
f569.codepoint=arrowtriangle_right_fill
arrowtriangle_right_fill=cupertino/arrowtriangle_right_fill.png
f56a.codepoint=arrowtriangle_right_square
arrowtriangle_right_square=cupertino/arrowtriangle_right_square.png
f56b.codepoint=arrowtriangle_right_square_fill
arrowtriangle_right_square_fill=cupertino/arrowtriangle_right_square_fill.png
f56c.codepoint=arrowtriangle_up
arrowtriangle_up=cupertino/arrowtriangle_up.png
f56d.codepoint=arrowtriangle_up_circle
arrowtriangle_up_circle=cupertino/arrowtriangle_up_circle.png
f56e.codepoint=arrowtriangle_up_circle_fill
arrowtriangle_up_circle_fill=cupertino/arrowtriangle_up_circle_fill.png
f56f.codepoint=arrowtriangle_up_fill
arrowtriangle_up_fill=cupertino/arrowtriangle_up_fill.png
f570.codepoint=arrowtriangle_up_square
arrowtriangle_up_square=cupertino/arrowtriangle_up_square.png
f571.codepoint=arrowtriangle_up_square_fill
arrowtriangle_up_square_fill=cupertino/arrowtriangle_up_square_fill.png
f572.codepoint=asterisk_circle
asterisk_circle=cupertino/asterisk_circle.png
f573.codepoint=asterisk_circle_fill
asterisk_circle_fill=cupertino/asterisk_circle_fill.png
f574.codepoint=at
at=cupertino/at.png
f575.codepoint=at_badge_minus
at_badge_minus=cupertino/at_badge_minus.png
f576.codepoint=at_badge_plus
at_badge_plus=cupertino/at_badge_plus.png
f8af.codepoint=at_circle
at_circle=cupertino/at_circle.png
f8b0.codepoint=at_circle_fill
at_circle_fill=cupertino/at_circle_fill.png
f3cf.codepoint=back
back=cupertino/back.png
f577.codepoint=backward
backward=cupertino/backward.png
f578.codepoint=backward_end
backward_end=cupertino/backward_end.png
f579.codepoint=backward_end_alt
backward_end_alt=cupertino/backward_end_alt.png
f57a.codepoint=backward_end_alt_fill
backward_end_alt_fill=cupertino/backward_end_alt_fill.png
f57b.codepoint=backward_end_fill
backward_end_fill=cupertino/backward_end_fill.png
f57c.codepoint=backward_fill
backward_fill=cupertino/backward_fill.png
f57d.codepoint=badge_plus_radiowaves_right
badge_plus_radiowaves_right=cupertino/badge_plus_radiowaves_right.png
f57e.codepoint=bag
bag=cupertino/bag.png
f57f.codepoint=bag_badge_minus
bag_badge_minus=cupertino/bag_badge_minus.png
f580.codepoint=bag_badge_plus
bag_badge_plus=cupertino/bag_badge_plus.png
f581.codepoint=bag_fill
bag_fill=cupertino/bag_fill.png
f582.codepoint=bag_fill_badge_minus
bag_fill_badge_minus=cupertino/bag_fill_badge_minus.png
f583.codepoint=bag_fill_badge_plus
bag_fill_badge_plus=cupertino/bag_fill_badge_plus.png
f584.codepoint=bandage
bandage=cupertino/bandage.png
f585.codepoint=bandage_fill
bandage_fill=cupertino/bandage_fill.png
f586.codepoint=barcode
barcode=cupertino/barcode.png
f587.codepoint=barcode_viewfinder
barcode_viewfinder=cupertino/barcode_viewfinder.png
f8b1.codepoint=bars
bars=cupertino/bars.png
f112.codepoint=battery_0
battery_0=cupertino/battery_0.png
f113.codepoint=battery_100
battery_100=cupertino/battery_100.png
f115.codepoint=battery_25
battery_25=cupertino/battery_25.png
# f115.codepoint=battery_25_percent
battery_25_percent=cupertino/battery_25_percent.png
f114.codepoint=battery_75_percent
battery_75_percent=cupertino/battery_75_percent.png
f111.codepoint=battery_charging
battery_charging=cupertino/battery_charging.png
# f112.codepoint=battery_empty
battery_empty=cupertino/battery_empty.png
# f113.codepoint=battery_full
battery_full=cupertino/battery_full.png
f588.codepoint=bed_double
bed_double=cupertino/bed_double.png
f589.codepoint=bed_double_fill
bed_double_fill=cupertino/bed_double_fill.png
f3e1.codepoint=bell
bell=cupertino/bell.png
f58a.codepoint=bell_circle
bell_circle=cupertino/bell_circle.png
f58b.codepoint=bell_circle_fill
bell_circle_fill=cupertino/bell_circle_fill.png
f3e2.codepoint=bell_fill
bell_fill=cupertino/bell_fill.png
f58c.codepoint=bell_slash
bell_slash=cupertino/bell_slash.png
f58d.codepoint=bell_slash_fill
bell_slash_fill=cupertino/bell_slash_fill.png
# f3e2.codepoint=bell_solid
bell_solid=cupertino/bell_solid.png
f58e.codepoint=bin_xmark
bin_xmark=cupertino/bin_xmark.png
f58f.codepoint=bin_xmark_fill
bin_xmark_fill=cupertino/bin_xmark_fill.png
f8b2.codepoint=bitcoin
bitcoin=cupertino/bitcoin.png
f8b3.codepoint=bitcoin_circle
bitcoin_circle=cupertino/bitcoin_circle.png
f8b4.codepoint=bitcoin_circle_fill
bitcoin_circle_fill=cupertino/bitcoin_circle_fill.png
f116.codepoint=bluetooth
bluetooth=cupertino/bluetooth.png
f590.codepoint=bold
bold=cupertino/bold.png
f591.codepoint=bold_italic_underline
bold_italic_underline=cupertino/bold_italic_underline.png
f592.codepoint=bold_underline
bold_underline=cupertino/bold_underline.png
f593.codepoint=bolt
bolt=cupertino/bolt.png
f594.codepoint=bolt_badge_a
bolt_badge_a=cupertino/bolt_badge_a.png
f595.codepoint=bolt_badge_a_fill
bolt_badge_a_fill=cupertino/bolt_badge_a_fill.png
f596.codepoint=bolt_circle
bolt_circle=cupertino/bolt_circle.png
f597.codepoint=bolt_circle_fill
bolt_circle_fill=cupertino/bolt_circle_fill.png
f598.codepoint=bolt_fill
bolt_fill=cupertino/bolt_fill.png
f599.codepoint=bolt_horizontal
bolt_horizontal=cupertino/bolt_horizontal.png
f59a.codepoint=bolt_horizontal_circle
bolt_horizontal_circle=cupertino/bolt_horizontal_circle.png
f59b.codepoint=bolt_horizontal_circle_fill
bolt_horizontal_circle_fill=cupertino/bolt_horizontal_circle_fill.png
f59c.codepoint=bolt_horizontal_fill
bolt_horizontal_fill=cupertino/bolt_horizontal_fill.png
f59d.codepoint=bolt_slash
bolt_slash=cupertino/bolt_slash.png
f59e.codepoint=bolt_slash_fill
bolt_slash_fill=cupertino/bolt_slash_fill.png
f3e7.codepoint=book
book=cupertino/book.png
f59f.codepoint=book_circle
book_circle=cupertino/book_circle.png
f5a0.codepoint=book_circle_fill
book_circle_fill=cupertino/book_circle_fill.png
f3e8.codepoint=book_fill
book_fill=cupertino/book_fill.png
# f3e8.codepoint=book_solid
book_solid=cupertino/book_solid.png
f3e9.codepoint=bookmark
bookmark=cupertino/bookmark.png
f3ea.codepoint=bookmark_fill
bookmark_fill=cupertino/bookmark_fill.png
# f3ea.codepoint=bookmark_solid
bookmark_solid=cupertino/bookmark_solid.png
f5a1.codepoint=briefcase
briefcase=cupertino/briefcase.png
f5a2.codepoint=briefcase_fill
briefcase_fill=cupertino/briefcase_fill.png
f4b6.codepoint=brightness
brightness=cupertino/brightness.png
f4b7.codepoint=brightness_solid
brightness_solid=cupertino/brightness_solid.png
f5a3.codepoint=bubble_left
bubble_left=cupertino/bubble_left.png
f5a4.codepoint=bubble_left_bubble_right
bubble_left_bubble_right=cupertino/bubble_left_bubble_right.png
f5a5.codepoint=bubble_left_bubble_right_fill
bubble_left_bubble_right_fill=cupertino/bubble_left_bubble_right_fill.png
f5a6.codepoint=bubble_left_fill
bubble_left_fill=cupertino/bubble_left_fill.png
f5a7.codepoint=bubble_middle_bottom
bubble_middle_bottom=cupertino/bubble_middle_bottom.png
f5a8.codepoint=bubble_middle_bottom_fill
bubble_middle_bottom_fill=cupertino/bubble_middle_bottom_fill.png
f5a9.codepoint=bubble_middle_top
bubble_middle_top=cupertino/bubble_middle_top.png
f5aa.codepoint=bubble_middle_top_fill
bubble_middle_top_fill=cupertino/bubble_middle_top_fill.png
f5ab.codepoint=bubble_right
bubble_right=cupertino/bubble_right.png
f5ac.codepoint=bubble_right_fill
bubble_right_fill=cupertino/bubble_right_fill.png
f8b5.codepoint=building_2_fill
building_2_fill=cupertino/building_2_fill.png
f5ad.codepoint=burn
burn=cupertino/burn.png
f5ae.codepoint=burst
burst=cupertino/burst.png
f5af.codepoint=burst_fill
burst_fill=cupertino/burst_fill.png
f36d.codepoint=bus
bus=cupertino/bus.png
f5b0.codepoint=calendar
calendar=cupertino/calendar.png
f5b1.codepoint=calendar_badge_minus
calendar_badge_minus=cupertino/calendar_badge_minus.png
f5b2.codepoint=calendar_badge_plus
calendar_badge_plus=cupertino/calendar_badge_plus.png
f5b3.codepoint=calendar_circle
calendar_circle=cupertino/calendar_circle.png
f5b4.codepoint=calendar_circle_fill
calendar_circle_fill=cupertino/calendar_circle_fill.png
f8b6.codepoint=calendar_today
calendar_today=cupertino/calendar_today.png
f3f5.codepoint=camera
camera=cupertino/camera.png
f5b5.codepoint=camera_circle
camera_circle=cupertino/camera_circle.png
f5b6.codepoint=camera_circle_fill
camera_circle_fill=cupertino/camera_circle_fill.png
f3f6.codepoint=camera_fill
camera_fill=cupertino/camera_fill.png
f5b7.codepoint=camera_on_rectangle
camera_on_rectangle=cupertino/camera_on_rectangle.png
f5b8.codepoint=camera_on_rectangle_fill
camera_on_rectangle_fill=cupertino/camera_on_rectangle_fill.png
f49e.codepoint=camera_rotate
camera_rotate=cupertino/camera_rotate.png
f49f.codepoint=camera_rotate_fill
camera_rotate_fill=cupertino/camera_rotate_fill.png
f5b9.codepoint=camera_viewfinder
camera_viewfinder=cupertino/camera_viewfinder.png
f5ba.codepoint=capslock
capslock=cupertino/capslock.png
f5bb.codepoint=capslock_fill
capslock_fill=cupertino/capslock_fill.png
f5bc.codepoint=capsule
capsule=cupertino/capsule.png
f5bd.codepoint=capsule_fill
capsule_fill=cupertino/capsule_fill.png
f5be.codepoint=captions_bubble
captions_bubble=cupertino/captions_bubble.png
f5bf.codepoint=captions_bubble_fill
captions_bubble_fill=cupertino/captions_bubble_fill.png
f36f.codepoint=car
car=cupertino/car.png
f2c1.codepoint=car_detailed
car_detailed=cupertino/car_detailed.png
# f36f.codepoint=car_fill
car_fill=cupertino/car_fill.png
f3f7.codepoint=cart
cart=cupertino/cart.png
f5c0.codepoint=cart_badge_minus
cart_badge_minus=cupertino/cart_badge_minus.png
f5c1.codepoint=cart_badge_plus
cart_badge_plus=cupertino/cart_badge_plus.png
f5c2.codepoint=cart_fill
cart_fill=cupertino/cart_fill.png
f5c3.codepoint=cart_fill_badge_minus
cart_fill_badge_minus=cupertino/cart_fill_badge_minus.png
f5c4.codepoint=cart_fill_badge_plus
cart_fill_badge_plus=cupertino/cart_fill_badge_plus.png
f5c5.codepoint=chart_bar
chart_bar=cupertino/chart_bar.png
f8b7.codepoint=chart_bar_alt_fill
chart_bar_alt_fill=cupertino/chart_bar_alt_fill.png
f8b8.codepoint=chart_bar_circle
chart_bar_circle=cupertino/chart_bar_circle.png
f8b9.codepoint=chart_bar_circle_fill
chart_bar_circle_fill=cupertino/chart_bar_circle_fill.png
f5c6.codepoint=chart_bar_fill
chart_bar_fill=cupertino/chart_bar_fill.png
f8ba.codepoint=chart_bar_square
chart_bar_square=cupertino/chart_bar_square.png
f8bb.codepoint=chart_bar_square_fill
chart_bar_square_fill=cupertino/chart_bar_square_fill.png
f5c7.codepoint=chart_pie
chart_pie=cupertino/chart_pie.png
f5c8.codepoint=chart_pie_fill
chart_pie_fill=cupertino/chart_pie_fill.png
f3fb.codepoint=chat_bubble
chat_bubble=cupertino/chat_bubble.png
f8bc.codepoint=chat_bubble_2
chat_bubble_2=cupertino/chat_bubble_2.png
f8bd.codepoint=chat_bubble_2_fill
chat_bubble_2_fill=cupertino/chat_bubble_2_fill.png
f8be.codepoint=chat_bubble_fill
chat_bubble_fill=cupertino/chat_bubble_fill.png
f8bf.codepoint=chat_bubble_text
chat_bubble_text=cupertino/chat_bubble_text.png
f8c0.codepoint=chat_bubble_text_fill
chat_bubble_text_fill=cupertino/chat_bubble_text_fill.png
f3fd.codepoint=check_mark
check_mark=cupertino/check_mark.png
f3fe.codepoint=check_mark_circled
check_mark_circled=cupertino/check_mark_circled.png
f3ff.codepoint=check_mark_circled_solid
check_mark_circled_solid=cupertino/check_mark_circled_solid.png
# f3fd.codepoint=checkmark
checkmark=cupertino/checkmark.png
f8c1.codepoint=checkmark_alt
checkmark_alt=cupertino/checkmark_alt.png
f8c2.codepoint=checkmark_alt_circle
checkmark_alt_circle=cupertino/checkmark_alt_circle.png
f8c3.codepoint=checkmark_alt_circle_fill
checkmark_alt_circle_fill=cupertino/checkmark_alt_circle_fill.png
# f3fe.codepoint=checkmark_circle
checkmark_circle=cupertino/checkmark_circle.png
# f3ff.codepoint=checkmark_circle_fill
checkmark_circle_fill=cupertino/checkmark_circle_fill.png
f5c9.codepoint=checkmark_rectangle
checkmark_rectangle=cupertino/checkmark_rectangle.png
f5ca.codepoint=checkmark_rectangle_fill
checkmark_rectangle_fill=cupertino/checkmark_rectangle_fill.png
f5cb.codepoint=checkmark_seal
checkmark_seal=cupertino/checkmark_seal.png
f5cc.codepoint=checkmark_seal_fill
checkmark_seal_fill=cupertino/checkmark_seal_fill.png
f5cd.codepoint=checkmark_shield
checkmark_shield=cupertino/checkmark_shield.png
f5ce.codepoint=checkmark_shield_fill
checkmark_shield_fill=cupertino/checkmark_shield_fill.png
f5cf.codepoint=checkmark_square
checkmark_square=cupertino/checkmark_square.png
f5d0.codepoint=checkmark_square_fill
checkmark_square_fill=cupertino/checkmark_square_fill.png
# f3cf.codepoint=chevron_back
chevron_back=cupertino/chevron_back.png
f5d1.codepoint=chevron_compact_down
chevron_compact_down=cupertino/chevron_compact_down.png
f5d2.codepoint=chevron_compact_left
chevron_compact_left=cupertino/chevron_compact_left.png
f5d3.codepoint=chevron_compact_right
chevron_compact_right=cupertino/chevron_compact_right.png
f5d4.codepoint=chevron_compact_up
chevron_compact_up=cupertino/chevron_compact_up.png
f5d5.codepoint=chevron_down
chevron_down=cupertino/chevron_down.png
f5d6.codepoint=chevron_down_circle
chevron_down_circle=cupertino/chevron_down_circle.png
f5d7.codepoint=chevron_down_circle_fill
chevron_down_circle_fill=cupertino/chevron_down_circle_fill.png
f5d8.codepoint=chevron_down_square
chevron_down_square=cupertino/chevron_down_square.png
f5d9.codepoint=chevron_down_square_fill
chevron_down_square_fill=cupertino/chevron_down_square_fill.png
f3d1.codepoint=chevron_forward
chevron_forward=cupertino/chevron_forward.png
f3d2.codepoint=chevron_left
chevron_left=cupertino/chevron_left.png
f5da.codepoint=chevron_left_2
chevron_left_2=cupertino/chevron_left_2.png
f5db.codepoint=chevron_left_circle
chevron_left_circle=cupertino/chevron_left_circle.png
f5dc.codepoint=chevron_left_circle_fill
chevron_left_circle_fill=cupertino/chevron_left_circle_fill.png
f5dd.codepoint=chevron_left_slash_chevron_right
chevron_left_slash_chevron_right=cupertino/chevron_left_slash_chevron_right.png
f5de.codepoint=chevron_left_square
chevron_left_square=cupertino/chevron_left_square.png
f5df.codepoint=chevron_left_square_fill
chevron_left_square_fill=cupertino/chevron_left_square_fill.png
f3d3.codepoint=chevron_right
chevron_right=cupertino/chevron_right.png
f5e0.codepoint=chevron_right_2
chevron_right_2=cupertino/chevron_right_2.png
f5e1.codepoint=chevron_right_circle
chevron_right_circle=cupertino/chevron_right_circle.png
f5e2.codepoint=chevron_right_circle_fill
chevron_right_circle_fill=cupertino/chevron_right_circle_fill.png
f5e3.codepoint=chevron_right_square
chevron_right_square=cupertino/chevron_right_square.png
f5e4.codepoint=chevron_right_square_fill
chevron_right_square_fill=cupertino/chevron_right_square_fill.png
f5e5.codepoint=chevron_up
chevron_up=cupertino/chevron_up.png
f5e6.codepoint=chevron_up_chevron_down
chevron_up_chevron_down=cupertino/chevron_up_chevron_down.png
f5e7.codepoint=chevron_up_circle
chevron_up_circle=cupertino/chevron_up_circle.png
f5e8.codepoint=chevron_up_circle_fill
chevron_up_circle_fill=cupertino/chevron_up_circle_fill.png
f5e9.codepoint=chevron_up_square
chevron_up_square=cupertino/chevron_up_square.png
f5ea.codepoint=chevron_up_square_fill
chevron_up_square_fill=cupertino/chevron_up_square_fill.png
f401.codepoint=circle
circle=cupertino/circle.png
f5eb.codepoint=circle_bottomthird_split
circle_bottomthird_split=cupertino/circle_bottomthird_split.png
f400.codepoint=circle_fill
circle_fill=cupertino/circle_fill.png
# f400.codepoint=circle_filled
circle_filled=cupertino/circle_filled.png
f5ec.codepoint=circle_grid_3x3
circle_grid_3x3=cupertino/circle_grid_3x3.png
f5ed.codepoint=circle_grid_3x3_fill
circle_grid_3x3_fill=cupertino/circle_grid_3x3_fill.png
f5ee.codepoint=circle_grid_hex
circle_grid_hex=cupertino/circle_grid_hex.png
f5ef.codepoint=circle_grid_hex_fill
circle_grid_hex_fill=cupertino/circle_grid_hex_fill.png
f5f0.codepoint=circle_lefthalf_fill
circle_lefthalf_fill=cupertino/circle_lefthalf_fill.png
f5f1.codepoint=circle_righthalf_fill
circle_righthalf_fill=cupertino/circle_righthalf_fill.png
f404.codepoint=clear
clear=cupertino/clear.png
f405.codepoint=clear_circled
clear_circled=cupertino/clear_circled.png
f406.codepoint=clear_circled_solid
clear_circled_solid=cupertino/clear_circled_solid.png
f5f3.codepoint=clear_fill
clear_fill=cupertino/clear_fill.png
f2d7.codepoint=clear_thick
clear_thick=cupertino/clear_thick.png
f36e.codepoint=clear_thick_circled
clear_thick_circled=cupertino/clear_thick_circled.png
f4be.codepoint=clock
clock=cupertino/clock.png
f403.codepoint=clock_fill
clock_fill=cupertino/clock_fill.png
f4bf.codepoint=clock_solid
clock_solid=cupertino/clock_solid.png
f5f4.codepoint=cloud
cloud=cupertino/cloud.png
f5f5.codepoint=cloud_bolt
cloud_bolt=cupertino/cloud_bolt.png
f5f6.codepoint=cloud_bolt_fill
cloud_bolt_fill=cupertino/cloud_bolt_fill.png
f5f7.codepoint=cloud_bolt_rain
cloud_bolt_rain=cupertino/cloud_bolt_rain.png
f5f8.codepoint=cloud_bolt_rain_fill
cloud_bolt_rain_fill=cupertino/cloud_bolt_rain_fill.png
f8c4.codepoint=cloud_download
cloud_download=cupertino/cloud_download.png
f8c5.codepoint=cloud_download_fill
cloud_download_fill=cupertino/cloud_download_fill.png
f5f9.codepoint=cloud_drizzle
cloud_drizzle=cupertino/cloud_drizzle.png
f5fa.codepoint=cloud_drizzle_fill
cloud_drizzle_fill=cupertino/cloud_drizzle_fill.png
f5fb.codepoint=cloud_fill
cloud_fill=cupertino/cloud_fill.png
f5fc.codepoint=cloud_fog
cloud_fog=cupertino/cloud_fog.png
f5fd.codepoint=cloud_fog_fill
cloud_fog_fill=cupertino/cloud_fog_fill.png
f5fe.codepoint=cloud_hail
cloud_hail=cupertino/cloud_hail.png
f5ff.codepoint=cloud_hail_fill
cloud_hail_fill=cupertino/cloud_hail_fill.png
f600.codepoint=cloud_heavyrain
cloud_heavyrain=cupertino/cloud_heavyrain.png
f601.codepoint=cloud_heavyrain_fill
cloud_heavyrain_fill=cupertino/cloud_heavyrain_fill.png
f602.codepoint=cloud_moon
cloud_moon=cupertino/cloud_moon.png
f603.codepoint=cloud_moon_bolt
cloud_moon_bolt=cupertino/cloud_moon_bolt.png
f604.codepoint=cloud_moon_bolt_fill
cloud_moon_bolt_fill=cupertino/cloud_moon_bolt_fill.png
f605.codepoint=cloud_moon_fill
cloud_moon_fill=cupertino/cloud_moon_fill.png
f606.codepoint=cloud_moon_rain
cloud_moon_rain=cupertino/cloud_moon_rain.png
f607.codepoint=cloud_moon_rain_fill
cloud_moon_rain_fill=cupertino/cloud_moon_rain_fill.png
f608.codepoint=cloud_rain
cloud_rain=cupertino/cloud_rain.png
f609.codepoint=cloud_rain_fill
cloud_rain_fill=cupertino/cloud_rain_fill.png
f60a.codepoint=cloud_sleet
cloud_sleet=cupertino/cloud_sleet.png
f60b.codepoint=cloud_sleet_fill
cloud_sleet_fill=cupertino/cloud_sleet_fill.png
f60c.codepoint=cloud_snow
cloud_snow=cupertino/cloud_snow.png
f60d.codepoint=cloud_snow_fill
cloud_snow_fill=cupertino/cloud_snow_fill.png
f60e.codepoint=cloud_sun
cloud_sun=cupertino/cloud_sun.png
f60f.codepoint=cloud_sun_bolt
cloud_sun_bolt=cupertino/cloud_sun_bolt.png
f610.codepoint=cloud_sun_bolt_fill
cloud_sun_bolt_fill=cupertino/cloud_sun_bolt_fill.png
f611.codepoint=cloud_sun_fill
cloud_sun_fill=cupertino/cloud_sun_fill.png
f612.codepoint=cloud_sun_rain
cloud_sun_rain=cupertino/cloud_sun_rain.png
f613.codepoint=cloud_sun_rain_fill
cloud_sun_rain_fill=cupertino/cloud_sun_rain_fill.png
f8c6.codepoint=cloud_upload
cloud_upload=cupertino/cloud_upload.png
f8c7.codepoint=cloud_upload_fill
cloud_upload_fill=cupertino/cloud_upload_fill.png
f3c9.codepoint=collections
collections=cupertino/collections.png
f3ca.codepoint=collections_solid
collections_solid=cupertino/collections_solid.png
f8c8.codepoint=color_filter
color_filter=cupertino/color_filter.png
f8c9.codepoint=color_filter_fill
color_filter_fill=cupertino/color_filter_fill.png
f614.codepoint=command
command=cupertino/command.png
f8ca.codepoint=compass
compass=cupertino/compass.png
f8cb.codepoint=compass_fill
compass_fill=cupertino/compass_fill.png
f615.codepoint=control
control=cupertino/control.png
# f3fb.codepoint=conversation_bubble
conversation_bubble=cupertino/conversation_bubble.png
f417.codepoint=create
create=cupertino/create.png
# f417.codepoint=create_solid
create_solid=cupertino/create_solid.png
f616.codepoint=creditcard
creditcard=cupertino/creditcard.png
f617.codepoint=creditcard_fill
creditcard_fill=cupertino/creditcard_fill.png
f618.codepoint=crop
crop=cupertino/crop.png
f619.codepoint=crop_rotate
crop_rotate=cupertino/crop_rotate.png
f61a.codepoint=cube
cube=cupertino/cube.png
f61b.codepoint=cube_box
cube_box=cupertino/cube_box.png
f61c.codepoint=cube_box_fill
cube_box_fill=cupertino/cube_box_fill.png
f61d.codepoint=cube_fill
cube_fill=cupertino/cube_fill.png
f61e.codepoint=cursor_rays
cursor_rays=cupertino/cursor_rays.png
f61f.codepoint=decrease_indent
decrease_indent=cupertino/decrease_indent.png
f620.codepoint=decrease_quotelevel
decrease_quotelevel=cupertino/decrease_quotelevel.png
f4c4.codepoint=delete
delete=cupertino/delete.png
f621.codepoint=delete_left
delete_left=cupertino/delete_left.png
f622.codepoint=delete_left_fill
delete_left_fill=cupertino/delete_left_fill.png
f623.codepoint=delete_right
delete_right=cupertino/delete_right.png
f624.codepoint=delete_right_fill
delete_right_fill=cupertino/delete_right_fill.png
f37f.codepoint=delete_simple
delete_simple=cupertino/delete_simple.png
f4c5.codepoint=delete_solid
delete_solid=cupertino/delete_solid.png
f625.codepoint=desktopcomputer
desktopcomputer=cupertino/desktopcomputer.png
f8cc.codepoint=device_desktop
device_desktop=cupertino/device_desktop.png
f8cd.codepoint=device_laptop
device_laptop=cupertino/device_laptop.png
f8ce.codepoint=device_phone_landscape
device_phone_landscape=cupertino/device_phone_landscape.png
f8cf.codepoint=device_phone_portrait
device_phone_portrait=cupertino/device_phone_portrait.png
f626.codepoint=dial
dial=cupertino/dial.png
f627.codepoint=dial_fill
dial_fill=cupertino/dial_fill.png
f628.codepoint=divide
divide=cupertino/divide.png
f629.codepoint=divide_circle
divide_circle=cupertino/divide_circle.png
f62a.codepoint=divide_circle_fill
divide_circle_fill=cupertino/divide_circle_fill.png
f62b.codepoint=divide_square
divide_square=cupertino/divide_square.png
f62c.codepoint=divide_square_fill
divide_square_fill=cupertino/divide_square_fill.png
f62d.codepoint=doc
doc=cupertino/doc.png
f62e.codepoint=doc_append
doc_append=cupertino/doc_append.png
f8d0.codepoint=doc_chart
doc_chart=cupertino/doc_chart.png
f8d1.codepoint=doc_chart_fill
doc_chart_fill=cupertino/doc_chart_fill.png
f8d2.codepoint=doc_checkmark
doc_checkmark=cupertino/doc_checkmark.png
f8d3.codepoint=doc_checkmark_fill
doc_checkmark_fill=cupertino/doc_checkmark_fill.png
f62f.codepoint=doc_circle
doc_circle=cupertino/doc_circle.png
f630.codepoint=doc_circle_fill
doc_circle_fill=cupertino/doc_circle_fill.png
f631.codepoint=doc_fill
doc_fill=cupertino/doc_fill.png
f632.codepoint=doc_on_clipboard
doc_on_clipboard=cupertino/doc_on_clipboard.png
f633.codepoint=doc_on_clipboard_fill
doc_on_clipboard_fill=cupertino/doc_on_clipboard_fill.png
f634.codepoint=doc_on_doc
doc_on_doc=cupertino/doc_on_doc.png
f635.codepoint=doc_on_doc_fill
doc_on_doc_fill=cupertino/doc_on_doc_fill.png
f8d4.codepoint=doc_person
doc_person=cupertino/doc_person.png
f8d5.codepoint=doc_person_fill
doc_person_fill=cupertino/doc_person_fill.png
f636.codepoint=doc_plaintext
doc_plaintext=cupertino/doc_plaintext.png
f637.codepoint=doc_richtext
doc_richtext=cupertino/doc_richtext.png
f638.codepoint=doc_text
doc_text=cupertino/doc_text.png
f639.codepoint=doc_text_fill
doc_text_fill=cupertino/doc_text_fill.png
f63a.codepoint=doc_text_search
doc_text_search=cupertino/doc_text_search.png
f63b.codepoint=doc_text_viewfinder
doc_text_viewfinder=cupertino/doc_text_viewfinder.png
f63c.codepoint=dot_radiowaves_left_right
dot_radiowaves_left_right=cupertino/dot_radiowaves_left_right.png
f63d.codepoint=dot_radiowaves_right
dot_radiowaves_right=cupertino/dot_radiowaves_right.png
f63e.codepoint=dot_square
dot_square=cupertino/dot_square.png
f63f.codepoint=dot_square_fill
dot_square_fill=cupertino/dot_square_fill.png
f46c.codepoint=double_music_note
double_music_note=cupertino/double_music_note.png
# f35d.codepoint=down_arrow
down_arrow=cupertino/down_arrow.png
f8d6.codepoint=download_circle
download_circle=cupertino/download_circle.png
f8d7.codepoint=download_circle_fill
download_circle_fill=cupertino/download_circle_fill.png
f8d8.codepoint=drop
drop=cupertino/drop.png
f8d9.codepoint=drop_fill
drop_fill=cupertino/drop_fill.png
f640.codepoint=drop_triangle
drop_triangle=cupertino/drop_triangle.png
f641.codepoint=drop_triangle_fill
drop_triangle_fill=cupertino/drop_triangle_fill.png
f642.codepoint=ear
ear=cupertino/ear.png
f643.codepoint=eject
eject=cupertino/eject.png
f644.codepoint=eject_fill
eject_fill=cupertino/eject_fill.png
f645.codepoint=ellipses_bubble
ellipses_bubble=cupertino/ellipses_bubble.png
f646.codepoint=ellipses_bubble_fill
ellipses_bubble_fill=cupertino/ellipses_bubble_fill.png
f46a.codepoint=ellipsis
ellipsis=cupertino/ellipsis.png
f647.codepoint=ellipsis_circle
ellipsis_circle=cupertino/ellipsis_circle.png
f648.codepoint=ellipsis_circle_fill
ellipsis_circle_fill=cupertino/ellipsis_circle_fill.png
f8da.codepoint=ellipsis_vertical
ellipsis_vertical=cupertino/ellipsis_vertical.png
f8db.codepoint=ellipsis_vertical_circle
ellipsis_vertical_circle=cupertino/ellipsis_vertical_circle.png
f8dc.codepoint=ellipsis_vertical_circle_fill
ellipsis_vertical_circle_fill=cupertino/ellipsis_vertical_circle_fill.png
f422.codepoint=envelope
envelope=cupertino/envelope.png
f649.codepoint=envelope_badge
envelope_badge=cupertino/envelope_badge.png
f64a.codepoint=envelope_badge_fill
envelope_badge_fill=cupertino/envelope_badge_fill.png
f64b.codepoint=envelope_circle
envelope_circle=cupertino/envelope_circle.png
f64c.codepoint=envelope_circle_fill
envelope_circle_fill=cupertino/envelope_circle_fill.png
f423.codepoint=envelope_fill
envelope_fill=cupertino/envelope_fill.png
f64d.codepoint=envelope_open
envelope_open=cupertino/envelope_open.png
f64e.codepoint=envelope_open_fill
envelope_open_fill=cupertino/envelope_open_fill.png
f64f.codepoint=equal
equal=cupertino/equal.png
f650.codepoint=equal_circle
equal_circle=cupertino/equal_circle.png
f651.codepoint=equal_circle_fill
equal_circle_fill=cupertino/equal_circle_fill.png
f652.codepoint=equal_square
equal_square=cupertino/equal_square.png
f653.codepoint=equal_square_fill
equal_square_fill=cupertino/equal_square_fill.png
f654.codepoint=escape
escape=cupertino/escape.png
f655.codepoint=exclamationmark
exclamationmark=cupertino/exclamationmark.png
f656.codepoint=exclamationmark_bubble
exclamationmark_bubble=cupertino/exclamationmark_bubble.png
f657.codepoint=exclamationmark_bubble_fill
exclamationmark_bubble_fill=cupertino/exclamationmark_bubble_fill.png
f658.codepoint=exclamationmark_circle
exclamationmark_circle=cupertino/exclamationmark_circle.png
f659.codepoint=exclamationmark_circle_fill
exclamationmark_circle_fill=cupertino/exclamationmark_circle_fill.png
f65a.codepoint=exclamationmark_octagon
exclamationmark_octagon=cupertino/exclamationmark_octagon.png
f65b.codepoint=exclamationmark_octagon_fill
exclamationmark_octagon_fill=cupertino/exclamationmark_octagon_fill.png
f65c.codepoint=exclamationmark_shield
exclamationmark_shield=cupertino/exclamationmark_shield.png
f65d.codepoint=exclamationmark_shield_fill
exclamationmark_shield_fill=cupertino/exclamationmark_shield_fill.png
f65e.codepoint=exclamationmark_square
exclamationmark_square=cupertino/exclamationmark_square.png
f65f.codepoint=exclamationmark_square_fill
exclamationmark_square_fill=cupertino/exclamationmark_square_fill.png
f660.codepoint=exclamationmark_triangle
exclamationmark_triangle=cupertino/exclamationmark_triangle.png
f661.codepoint=exclamationmark_triangle_fill
exclamationmark_triangle_fill=cupertino/exclamationmark_triangle_fill.png
f424.codepoint=eye
eye=cupertino/eye.png
f425.codepoint=eye_fill
eye_fill=cupertino/eye_fill.png
f662.codepoint=eye_slash
eye_slash=cupertino/eye_slash.png
f663.codepoint=eye_slash_fill
eye_slash_fill=cupertino/eye_slash_fill.png
# f425.codepoint=eye_solid
eye_solid=cupertino/eye_solid.png
f664.codepoint=eyedropper
eyedropper=cupertino/eyedropper.png
f665.codepoint=eyedropper_full
eyedropper_full=cupertino/eyedropper_full.png
f666.codepoint=eyedropper_halffull
eyedropper_halffull=cupertino/eyedropper_halffull.png
f667.codepoint=eyeglasses
eyeglasses=cupertino/eyeglasses.png
f668.codepoint=f_cursive
f_cursive=cupertino/f_cursive.png
f669.codepoint=f_cursive_circle
f_cursive_circle=cupertino/f_cursive_circle.png
f66a.codepoint=f_cursive_circle_fill
f_cursive_circle_fill=cupertino/f_cursive_circle_fill.png
f66b.codepoint=film
film=cupertino/film.png
f66c.codepoint=film_fill
film_fill=cupertino/film_fill.png
f42c.codepoint=flag
flag=cupertino/flag.png
f66d.codepoint=flag_circle
flag_circle=cupertino/flag_circle.png
f66e.codepoint=flag_circle_fill
flag_circle_fill=cupertino/flag_circle_fill.png
f66f.codepoint=flag_fill
flag_fill=cupertino/flag_fill.png
f670.codepoint=flag_slash
flag_slash=cupertino/flag_slash.png
f671.codepoint=flag_slash_fill
flag_slash_fill=cupertino/flag_slash_fill.png
f672.codepoint=flame
flame=cupertino/flame.png
f673.codepoint=flame_fill
flame_fill=cupertino/flame_fill.png
f8dd.codepoint=floppy_disk
floppy_disk=cupertino/floppy_disk.png
f674.codepoint=flowchart
flowchart=cupertino/flowchart.png
f675.codepoint=flowchart_fill
flowchart_fill=cupertino/flowchart_fill.png
f434.codepoint=folder
folder=cupertino/folder.png
f676.codepoint=folder_badge_minus
folder_badge_minus=cupertino/folder_badge_minus.png
f677.codepoint=folder_badge_person_crop
folder_badge_person_crop=cupertino/folder_badge_person_crop.png
f678.codepoint=folder_badge_plus
folder_badge_plus=cupertino/folder_badge_plus.png
f679.codepoint=folder_circle
folder_circle=cupertino/folder_circle.png
f67a.codepoint=folder_circle_fill
folder_circle_fill=cupertino/folder_circle_fill.png
f435.codepoint=folder_fill
folder_fill=cupertino/folder_fill.png
f67b.codepoint=folder_fill_badge_minus
folder_fill_badge_minus=cupertino/folder_fill_badge_minus.png
f67c.codepoint=folder_fill_badge_person_crop
folder_fill_badge_person_crop=cupertino/folder_fill_badge_person_crop.png
f67d.codepoint=folder_fill_badge_plus
folder_fill_badge_plus=cupertino/folder_fill_badge_plus.png
f38a.codepoint=folder_open
folder_open=cupertino/folder_open.png
# f435.codepoint=folder_solid
folder_solid=cupertino/folder_solid.png
# f3d1.codepoint=forward
forward=cupertino/forward.png
f67f.codepoint=forward_end
forward_end=cupertino/forward_end.png
f680.codepoint=forward_end_alt
forward_end_alt=cupertino/forward_end_alt.png
f681.codepoint=forward_end_alt_fill
forward_end_alt_fill=cupertino/forward_end_alt_fill.png
f682.codepoint=forward_end_fill
forward_end_fill=cupertino/forward_end_fill.png
f683.codepoint=forward_fill
forward_fill=cupertino/forward_fill.png
# f386.codepoint=fullscreen
fullscreen=cupertino/fullscreen.png
# f37d.codepoint=fullscreen_exit
fullscreen_exit=cupertino/fullscreen_exit.png
f684.codepoint=function
function=cupertino/function.png
f685.codepoint=fx
fx=cupertino/fx.png
f43a.codepoint=game_controller
game_controller=cupertino/game_controller.png
f43b.codepoint=game_controller_solid
game_controller_solid=cupertino/game_controller_solid.png
# f43a.codepoint=gamecontroller
gamecontroller=cupertino/gamecontroller.png
f8de.codepoint=gamecontroller_alt_fill
gamecontroller_alt_fill=cupertino/gamecontroller_alt_fill.png
# f43b.codepoint=gamecontroller_fill
gamecontroller_fill=cupertino/gamecontroller_fill.png
f686.codepoint=gauge
gauge=cupertino/gauge.png
f687.codepoint=gauge_badge_minus
gauge_badge_minus=cupertino/gauge_badge_minus.png
f688.codepoint=gauge_badge_plus
gauge_badge_plus=cupertino/gauge_badge_plus.png
f43c.codepoint=gear
gear=cupertino/gear.png
# f43c.codepoint=gear_alt
gear_alt=cupertino/gear_alt.png
f43d.codepoint=gear_alt_fill
gear_alt_fill=cupertino/gear_alt_fill.png
f2f7.codepoint=gear_big
gear_big=cupertino/gear_big.png
# f43d.codepoint=gear_solid
gear_solid=cupertino/gear_solid.png
f689.codepoint=gift
gift=cupertino/gift.png
f68a.codepoint=gift_alt
gift_alt=cupertino/gift_alt.png
f68b.codepoint=gift_alt_fill
gift_alt_fill=cupertino/gift_alt_fill.png
f68c.codepoint=gift_fill
gift_fill=cupertino/gift_fill.png
f68d.codepoint=globe
globe=cupertino/globe.png
f68e.codepoint=gobackward
gobackward=cupertino/gobackward.png
f68f.codepoint=gobackward_10
gobackward_10=cupertino/gobackward_10.png
f690.codepoint=gobackward_15
gobackward_15=cupertino/gobackward_15.png
f691.codepoint=gobackward_30
gobackward_30=cupertino/gobackward_30.png
f692.codepoint=gobackward_45
gobackward_45=cupertino/gobackward_45.png
f693.codepoint=gobackward_60
gobackward_60=cupertino/gobackward_60.png
f694.codepoint=gobackward_75
gobackward_75=cupertino/gobackward_75.png
f695.codepoint=gobackward_90
gobackward_90=cupertino/gobackward_90.png
f696.codepoint=gobackward_minus
gobackward_minus=cupertino/gobackward_minus.png
f697.codepoint=goforward
goforward=cupertino/goforward.png
f698.codepoint=goforward_10
goforward_10=cupertino/goforward_10.png
f699.codepoint=goforward_15
goforward_15=cupertino/goforward_15.png
f69a.codepoint=goforward_30
goforward_30=cupertino/goforward_30.png
f69b.codepoint=goforward_45
goforward_45=cupertino/goforward_45.png
f69c.codepoint=goforward_60
goforward_60=cupertino/goforward_60.png
f69d.codepoint=goforward_75
goforward_75=cupertino/goforward_75.png
f69e.codepoint=goforward_90
goforward_90=cupertino/goforward_90.png
f69f.codepoint=goforward_plus
goforward_plus=cupertino/goforward_plus.png
f8df.codepoint=graph_circle
graph_circle=cupertino/graph_circle.png
f8e0.codepoint=graph_circle_fill
graph_circle_fill=cupertino/graph_circle_fill.png
f8e1.codepoint=graph_square
graph_square=cupertino/graph_square.png
f8e2.codepoint=graph_square_fill
graph_square_fill=cupertino/graph_square_fill.png
f6a0.codepoint=greaterthan
greaterthan=cupertino/greaterthan.png
f6a1.codepoint=greaterthan_circle
greaterthan_circle=cupertino/greaterthan_circle.png
f6a2.codepoint=greaterthan_circle_fill
greaterthan_circle_fill=cupertino/greaterthan_circle_fill.png
f6a3.codepoint=greaterthan_square
greaterthan_square=cupertino/greaterthan_square.png
f6a4.codepoint=greaterthan_square_fill
greaterthan_square_fill=cupertino/greaterthan_square_fill.png
f6a5.codepoint=grid
grid=cupertino/grid.png
f6a6.codepoint=grid_circle
grid_circle=cupertino/grid_circle.png
f6a7.codepoint=grid_circle_fill
grid_circle_fill=cupertino/grid_circle_fill.png
f47b.codepoint=group
group=cupertino/group.png
f47c.codepoint=group_solid
group_solid=cupertino/group_solid.png
f6a8.codepoint=guitars
guitars=cupertino/guitars.png
f6a9.codepoint=hammer
hammer=cupertino/hammer.png
f6aa.codepoint=hammer_fill
hammer_fill=cupertino/hammer_fill.png
f6ab.codepoint=hand_draw
hand_draw=cupertino/hand_draw.png
f6ac.codepoint=hand_draw_fill
hand_draw_fill=cupertino/hand_draw_fill.png
f6ad.codepoint=hand_point_left
hand_point_left=cupertino/hand_point_left.png
f6ae.codepoint=hand_point_left_fill
hand_point_left_fill=cupertino/hand_point_left_fill.png
f6af.codepoint=hand_point_right
hand_point_right=cupertino/hand_point_right.png
f6b0.codepoint=hand_point_right_fill
hand_point_right_fill=cupertino/hand_point_right_fill.png
f6b1.codepoint=hand_raised
hand_raised=cupertino/hand_raised.png
f6b2.codepoint=hand_raised_fill
hand_raised_fill=cupertino/hand_raised_fill.png
f6b3.codepoint=hand_raised_slash
hand_raised_slash=cupertino/hand_raised_slash.png
f6b4.codepoint=hand_raised_slash_fill
hand_raised_slash_fill=cupertino/hand_raised_slash_fill.png
f6b5.codepoint=hand_thumbsdown
hand_thumbsdown=cupertino/hand_thumbsdown.png
f6b6.codepoint=hand_thumbsdown_fill
hand_thumbsdown_fill=cupertino/hand_thumbsdown_fill.png
f6b7.codepoint=hand_thumbsup
hand_thumbsup=cupertino/hand_thumbsup.png
f6b8.codepoint=hand_thumbsup_fill
hand_thumbsup_fill=cupertino/hand_thumbsup_fill.png
f6b9.codepoint=hare
hare=cupertino/hare.png
f6ba.codepoint=hare_fill
hare_fill=cupertino/hare_fill.png
f6bb.codepoint=headphones
headphones=cupertino/headphones.png
f442.codepoint=heart
heart=cupertino/heart.png
f6bc.codepoint=heart_circle
heart_circle=cupertino/heart_circle.png
f6bd.codepoint=heart_circle_fill
heart_circle_fill=cupertino/heart_circle_fill.png
f443.codepoint=heart_fill
heart_fill=cupertino/heart_fill.png
f6be.codepoint=heart_slash
heart_slash=cupertino/heart_slash.png
f6bf.codepoint=heart_slash_circle
heart_slash_circle=cupertino/heart_slash_circle.png
f6c0.codepoint=heart_slash_circle_fill
heart_slash_circle_fill=cupertino/heart_slash_circle_fill.png
f6c1.codepoint=heart_slash_fill
heart_slash_fill=cupertino/heart_slash_fill.png
# f443.codepoint=heart_solid
heart_solid=cupertino/heart_solid.png
f6c2.codepoint=helm
helm=cupertino/helm.png
f6c3.codepoint=hexagon
hexagon=cupertino/hexagon.png
f6c4.codepoint=hexagon_fill
hexagon_fill=cupertino/hexagon_fill.png
f6c5.codepoint=hifispeaker
hifispeaker=cupertino/hifispeaker.png
f6c6.codepoint=hifispeaker_fill
hifispeaker_fill=cupertino/hifispeaker_fill.png
f447.codepoint=home
home=cupertino/home.png
f6c7.codepoint=hourglass
hourglass=cupertino/hourglass.png
f6c8.codepoint=hourglass_bottomhalf_fill
hourglass_bottomhalf_fill=cupertino/hourglass_bottomhalf_fill.png
f6c9.codepoint=hourglass_tophalf_fill
hourglass_tophalf_fill=cupertino/hourglass_tophalf_fill.png
# f447.codepoint=house
house=cupertino/house.png
f8e3.codepoint=house_alt
house_alt=cupertino/house_alt.png
f8e4.codepoint=house_alt_fill
house_alt_fill=cupertino/house_alt_fill.png
f6ca.codepoint=house_fill
house_fill=cupertino/house_fill.png
f6cb.codepoint=hurricane
hurricane=cupertino/hurricane.png
f6cc.codepoint=increase_indent
increase_indent=cupertino/increase_indent.png
f6cd.codepoint=increase_quotelevel
increase_quotelevel=cupertino/increase_quotelevel.png
f449.codepoint=infinite
infinite=cupertino/infinite.png
f44c.codepoint=info
info=cupertino/info.png
# f44c.codepoint=info_circle
info_circle=cupertino/info_circle.png
f6cf.codepoint=info_circle_fill
info_circle_fill=cupertino/info_circle_fill.png
f6d0.codepoint=italic
italic=cupertino/italic.png
f6d1.codepoint=keyboard
keyboard=cupertino/keyboard.png
f6d2.codepoint=keyboard_chevron_compact_down
keyboard_chevron_compact_down=cupertino/keyboard_chevron_compact_down.png
f430.codepoint=lab_flask
lab_flask=cupertino/lab_flask.png
f431.codepoint=lab_flask_solid
lab_flask_solid=cupertino/lab_flask_solid.png
f6d3.codepoint=largecircle_fill_circle
largecircle_fill_circle=cupertino/largecircle_fill_circle.png
f6d4.codepoint=lasso
lasso=cupertino/lasso.png
f8e5.codepoint=layers
layers=cupertino/layers.png
f8e6.codepoint=layers_alt
layers_alt=cupertino/layers_alt.png
f8e7.codepoint=layers_alt_fill
layers_alt_fill=cupertino/layers_alt_fill.png
f8e8.codepoint=layers_fill
layers_fill=cupertino/layers_fill.png
f6d5.codepoint=leaf_arrow_circlepath
leaf_arrow_circlepath=cupertino/leaf_arrow_circlepath.png
# f3d2.codepoint=left_chevron
left_chevron=cupertino/left_chevron.png
f6d6.codepoint=lessthan
lessthan=cupertino/lessthan.png
f6d7.codepoint=lessthan_circle
lessthan_circle=cupertino/lessthan_circle.png
f6d8.codepoint=lessthan_circle_fill
lessthan_circle_fill=cupertino/lessthan_circle_fill.png
f6d9.codepoint=lessthan_square
lessthan_square=cupertino/lessthan_square.png
f6da.codepoint=lessthan_square_fill
lessthan_square_fill=cupertino/lessthan_square_fill.png
f6db.codepoint=light_max
light_max=cupertino/light_max.png
f6dc.codepoint=light_min
light_min=cupertino/light_min.png
f6dd.codepoint=lightbulb
lightbulb=cupertino/lightbulb.png
f6de.codepoint=lightbulb_fill
lightbulb_fill=cupertino/lightbulb_fill.png
f6df.codepoint=lightbulb_slash
lightbulb_slash=cupertino/lightbulb_slash.png
f6e0.codepoint=lightbulb_slash_fill
lightbulb_slash_fill=cupertino/lightbulb_slash_fill.png
f6e1.codepoint=line_horizontal_3
line_horizontal_3=cupertino/line_horizontal_3.png
f6e2.codepoint=line_horizontal_3_decrease
line_horizontal_3_decrease=cupertino/line_horizontal_3_decrease.png
f6e3.codepoint=line_horizontal_3_decrease_circle
line_horizontal_3_decrease_circle=cupertino/line_horizontal_3_decrease_circle.png
f6e4.codepoint=line_horizontal_3_decrease_circle_fill
line_horizontal_3_decrease_circle_fill=cupertino/line_horizontal_3_decrease_circle_fill.png
f6e5.codepoint=link
link=cupertino/link.png
f6e6.codepoint=link_circle
link_circle=cupertino/link_circle.png
f6e7.codepoint=link_circle_fill
link_circle_fill=cupertino/link_circle_fill.png
f6e8.codepoint=list_bullet
list_bullet=cupertino/list_bullet.png
f6e9.codepoint=list_bullet_below_rectangle
list_bullet_below_rectangle=cupertino/list_bullet_below_rectangle.png
f6ea.codepoint=list_bullet_indent
list_bullet_indent=cupertino/list_bullet_indent.png
f6eb.codepoint=list_dash
list_dash=cupertino/list_dash.png
f6ec.codepoint=list_number
list_number=cupertino/list_number.png
f6ed.codepoint=list_number_rtl
list_number_rtl=cupertino/list_number_rtl.png
f455.codepoint=location
location=cupertino/location.png
f6ef.codepoint=location_circle
location_circle=cupertino/location_circle.png
f6f0.codepoint=location_circle_fill
location_circle_fill=cupertino/location_circle_fill.png
f6f1.codepoint=location_fill
location_fill=cupertino/location_fill.png
f6f2.codepoint=location_north
location_north=cupertino/location_north.png
f6f3.codepoint=location_north_fill
location_north_fill=cupertino/location_north_fill.png
f6f4.codepoint=location_north_line
location_north_line=cupertino/location_north_line.png
f6f5.codepoint=location_north_line_fill
location_north_line_fill=cupertino/location_north_line_fill.png
f6f6.codepoint=location_slash
location_slash=cupertino/location_slash.png
f6f7.codepoint=location_slash_fill
location_slash_fill=cupertino/location_slash_fill.png
f456.codepoint=location_solid
location_solid=cupertino/location_solid.png
f4c8.codepoint=lock
lock=cupertino/lock.png
f6f8.codepoint=lock_circle
lock_circle=cupertino/lock_circle.png
f6f9.codepoint=lock_circle_fill
lock_circle_fill=cupertino/lock_circle_fill.png
f4c9.codepoint=lock_fill
lock_fill=cupertino/lock_fill.png
f6fa.codepoint=lock_open
lock_open=cupertino/lock_open.png
f6fb.codepoint=lock_open_fill
lock_open_fill=cupertino/lock_open_fill.png
f6fc.codepoint=lock_rotation
lock_rotation=cupertino/lock_rotation.png
f6fd.codepoint=lock_rotation_open
lock_rotation_open=cupertino/lock_rotation_open.png
f6fe.codepoint=lock_shield
lock_shield=cupertino/lock_shield.png
f6ff.codepoint=lock_shield_fill
lock_shield_fill=cupertino/lock_shield_fill.png
f700.codepoint=lock_slash
lock_slash=cupertino/lock_slash.png
f701.codepoint=lock_slash_fill
lock_slash_fill=cupertino/lock_slash_fill.png
# f449.codepoint=loop
loop=cupertino/loop.png
f44a.codepoint=loop_thick
loop_thick=cupertino/loop_thick.png
f702.codepoint=macwindow
macwindow=cupertino/macwindow.png
# f422.codepoint=mail
mail=cupertino/mail.png
# f423.codepoint=mail_solid
mail_solid=cupertino/mail_solid.png
f703.codepoint=map
map=cupertino/map.png
f704.codepoint=map_fill
map_fill=cupertino/map_fill.png
f705.codepoint=map_pin
map_pin=cupertino/map_pin.png
f706.codepoint=map_pin_ellipse
map_pin_ellipse=cupertino/map_pin_ellipse.png
f707.codepoint=map_pin_slash
map_pin_slash=cupertino/map_pin_slash.png
f708.codepoint=memories
memories=cupertino/memories.png
f709.codepoint=memories_badge_minus
memories_badge_minus=cupertino/memories_badge_minus.png
f70a.codepoint=memories_badge_plus
memories_badge_plus=cupertino/memories_badge_plus.png
f70b.codepoint=metronome
metronome=cupertino/metronome.png
f460.codepoint=mic
mic=cupertino/mic.png
f70c.codepoint=mic_circle
mic_circle=cupertino/mic_circle.png
f70d.codepoint=mic_circle_fill
mic_circle_fill=cupertino/mic_circle_fill.png
f461.codepoint=mic_fill
mic_fill=cupertino/mic_fill.png
f45f.codepoint=mic_off
mic_off=cupertino/mic_off.png
# f45f.codepoint=mic_slash
mic_slash=cupertino/mic_slash.png
f70e.codepoint=mic_slash_fill
mic_slash_fill=cupertino/mic_slash_fill.png
# f461.codepoint=mic_solid
mic_solid=cupertino/mic_solid.png
f70f.codepoint=minus
minus=cupertino/minus.png
f463.codepoint=minus_circle
minus_circle=cupertino/minus_circle.png
f710.codepoint=minus_circle_fill
minus_circle_fill=cupertino/minus_circle_fill.png
# f463.codepoint=minus_circled
minus_circled=cupertino/minus_circled.png
f711.codepoint=minus_rectangle
minus_rectangle=cupertino/minus_rectangle.png
f712.codepoint=minus_rectangle_fill
minus_rectangle_fill=cupertino/minus_rectangle_fill.png
f713.codepoint=minus_slash_plus
minus_slash_plus=cupertino/minus_slash_plus.png
f714.codepoint=minus_square
minus_square=cupertino/minus_square.png
f715.codepoint=minus_square_fill
minus_square_fill=cupertino/minus_square_fill.png
f8e9.codepoint=money_dollar
money_dollar=cupertino/money_dollar.png
f8ea.codepoint=money_dollar_circle
money_dollar_circle=cupertino/money_dollar_circle.png
f8eb.codepoint=money_dollar_circle_fill
money_dollar_circle_fill=cupertino/money_dollar_circle_fill.png
f8ec.codepoint=money_euro
money_euro=cupertino/money_euro.png
f8ed.codepoint=money_euro_circle
money_euro_circle=cupertino/money_euro_circle.png
f8ee.codepoint=money_euro_circle_fill
money_euro_circle_fill=cupertino/money_euro_circle_fill.png
f8ef.codepoint=money_pound
money_pound=cupertino/money_pound.png
f8f0.codepoint=money_pound_circle
money_pound_circle=cupertino/money_pound_circle.png
f8f1.codepoint=money_pound_circle_fill
money_pound_circle_fill=cupertino/money_pound_circle_fill.png
f8f2.codepoint=money_rubl
money_rubl=cupertino/money_rubl.png
f8f3.codepoint=money_rubl_circle
money_rubl_circle=cupertino/money_rubl_circle.png
f8f4.codepoint=money_rubl_circle_fill
money_rubl_circle_fill=cupertino/money_rubl_circle_fill.png
f8f5.codepoint=money_yen
money_yen=cupertino/money_yen.png
f8f6.codepoint=money_yen_circle
money_yen_circle=cupertino/money_yen_circle.png
f8f7.codepoint=money_yen_circle_fill
money_yen_circle_fill=cupertino/money_yen_circle_fill.png
f716.codepoint=moon
moon=cupertino/moon.png
f717.codepoint=moon_circle
moon_circle=cupertino/moon_circle.png
f718.codepoint=moon_circle_fill
moon_circle_fill=cupertino/moon_circle_fill.png
f719.codepoint=moon_fill
moon_fill=cupertino/moon_fill.png
f71a.codepoint=moon_stars
moon_stars=cupertino/moon_stars.png
f71b.codepoint=moon_stars_fill
moon_stars_fill=cupertino/moon_stars_fill.png
f71c.codepoint=moon_zzz
moon_zzz=cupertino/moon_zzz.png
f71d.codepoint=moon_zzz_fill
moon_zzz_fill=cupertino/moon_zzz_fill.png
f8f8.codepoint=move
move=cupertino/move.png
f71e.codepoint=multiply
multiply=cupertino/multiply.png
f71f.codepoint=multiply_circle
multiply_circle=cupertino/multiply_circle.png
f720.codepoint=multiply_circle_fill
multiply_circle_fill=cupertino/multiply_circle_fill.png
f721.codepoint=multiply_square
multiply_square=cupertino/multiply_square.png
f722.codepoint=multiply_square_fill
multiply_square_fill=cupertino/multiply_square_fill.png
f8f9.codepoint=music_albums
music_albums=cupertino/music_albums.png
f8fa.codepoint=music_albums_fill
music_albums_fill=cupertino/music_albums_fill.png
f723.codepoint=music_house
music_house=cupertino/music_house.png
f724.codepoint=music_house_fill
music_house_fill=cupertino/music_house_fill.png
f725.codepoint=music_mic
music_mic=cupertino/music_mic.png
f46b.codepoint=music_note
music_note=cupertino/music_note.png
# f46c.codepoint=music_note_2
music_note_2=cupertino/music_note_2.png
f726.codepoint=music_note_list
music_note_list=cupertino/music_note_list.png
f471.codepoint=news
news=cupertino/news.png
f472.codepoint=news_solid
news_solid=cupertino/news_solid.png
f727.codepoint=nosign
nosign=cupertino/nosign.png
f728.codepoint=number
number=cupertino/number.png
f729.codepoint=number_circle
number_circle=cupertino/number_circle.png
f72a.codepoint=number_circle_fill
number_circle_fill=cupertino/number_circle_fill.png
f72b.codepoint=number_square
number_square=cupertino/number_square.png
f72c.codepoint=number_square_fill
number_square_fill=cupertino/number_square_fill.png
f72d.codepoint=option
option=cupertino/option.png
# f4c8.codepoint=padlock
padlock=cupertino/padlock.png
# f4c9.codepoint=padlock_solid
padlock_solid=cupertino/padlock_solid.png
f72e.codepoint=paintbrush
paintbrush=cupertino/paintbrush.png
f72f.codepoint=paintbrush_fill
paintbrush_fill=cupertino/paintbrush_fill.png
f730.codepoint=pano
pano=cupertino/pano.png
f731.codepoint=pano_fill
pano_fill=cupertino/pano_fill.png
f732.codepoint=paperclip
paperclip=cupertino/paperclip.png
f733.codepoint=paperplane
paperplane=cupertino/paperplane.png
f734.codepoint=paperplane_fill
paperplane_fill=cupertino/paperplane_fill.png
f735.codepoint=paragraph
paragraph=cupertino/paragraph.png
f477.codepoint=pause
pause=cupertino/pause.png
f736.codepoint=pause_circle
pause_circle=cupertino/pause_circle.png
f737.codepoint=pause_circle_fill
pause_circle_fill=cupertino/pause_circle_fill.png
f478.codepoint=pause_fill
pause_fill=cupertino/pause_fill.png
f738.codepoint=pause_rectangle
pause_rectangle=cupertino/pause_rectangle.png
f739.codepoint=pause_rectangle_fill
pause_rectangle_fill=cupertino/pause_rectangle_fill.png
# f478.codepoint=pause_solid
pause_solid=cupertino/pause_solid.png
f479.codepoint=paw
paw=cupertino/paw.png
f47a.codepoint=paw_solid
paw_solid=cupertino/paw_solid.png
f2bf.codepoint=pen
pen=cupertino/pen.png
f37e.codepoint=pencil
pencil=cupertino/pencil.png
f73a.codepoint=pencil_circle
pencil_circle=cupertino/pencil_circle.png
f73b.codepoint=pencil_circle_fill
pencil_circle_fill=cupertino/pencil_circle_fill.png
f73c.codepoint=pencil_ellipsis_rectangle
pencil_ellipsis_rectangle=cupertino/pencil_ellipsis_rectangle.png
f73d.codepoint=pencil_outline
pencil_outline=cupertino/pencil_outline.png
f73e.codepoint=pencil_slash
pencil_slash=cupertino/pencil_slash.png
f73f.codepoint=percent
percent=cupertino/percent.png
f47d.codepoint=person
person=cupertino/person.png
f740.codepoint=person_2
person_2=cupertino/person_2.png
f8fb.codepoint=person_2_alt
person_2_alt=cupertino/person_2_alt.png
f741.codepoint=person_2_fill
person_2_fill=cupertino/person_2_fill.png
f742.codepoint=person_2_square_stack
person_2_square_stack=cupertino/person_2_square_stack.png
f743.codepoint=person_2_square_stack_fill
person_2_square_stack_fill=cupertino/person_2_square_stack_fill.png
# f47b.codepoint=person_3
person_3=cupertino/person_3.png
# f47c.codepoint=person_3_fill
person_3_fill=cupertino/person_3_fill.png
f47f.codepoint=person_add
person_add=cupertino/person_add.png
f480.codepoint=person_add_solid
person_add_solid=cupertino/person_add_solid.png
f8fc.codepoint=person_alt
person_alt=cupertino/person_alt.png
f8fd.codepoint=person_alt_circle
person_alt_circle=cupertino/person_alt_circle.png
f8fe.codepoint=person_alt_circle_fill
person_alt_circle_fill=cupertino/person_alt_circle_fill.png
f744.codepoint=person_badge_minus
person_badge_minus=cupertino/person_badge_minus.png
f745.codepoint=person_badge_minus_fill
person_badge_minus_fill=cupertino/person_badge_minus_fill.png
# f47f.codepoint=person_badge_plus
person_badge_plus=cupertino/person_badge_plus.png
# f480.codepoint=person_badge_plus_fill
person_badge_plus_fill=cupertino/person_badge_plus_fill.png
f746.codepoint=person_circle
person_circle=cupertino/person_circle.png
f747.codepoint=person_circle_fill
person_circle_fill=cupertino/person_circle_fill.png
f419.codepoint=person_crop_circle
person_crop_circle=cupertino/person_crop_circle.png
f748.codepoint=person_crop_circle_badge_checkmark
person_crop_circle_badge_checkmark=cupertino/person_crop_circle_badge_checkmark.png
f749.codepoint=person_crop_circle_badge_exclam
person_crop_circle_badge_exclam=cupertino/person_crop_circle_badge_exclam.png
f74a.codepoint=person_crop_circle_badge_minus
person_crop_circle_badge_minus=cupertino/person_crop_circle_badge_minus.png
f74b.codepoint=person_crop_circle_badge_plus
person_crop_circle_badge_plus=cupertino/person_crop_circle_badge_plus.png
f74c.codepoint=person_crop_circle_badge_xmark
person_crop_circle_badge_xmark=cupertino/person_crop_circle_badge_xmark.png
f74d.codepoint=person_crop_circle_fill
person_crop_circle_fill=cupertino/person_crop_circle_fill.png
f74e.codepoint=person_crop_circle_fill_badge_checkmark
person_crop_circle_fill_badge_checkmark=cupertino/person_crop_circle_fill_badge_checkmark.png
f74f.codepoint=person_crop_circle_fill_badge_exclam
person_crop_circle_fill_badge_exclam=cupertino/person_crop_circle_fill_badge_exclam.png
f750.codepoint=person_crop_circle_fill_badge_minus
person_crop_circle_fill_badge_minus=cupertino/person_crop_circle_fill_badge_minus.png
f751.codepoint=person_crop_circle_fill_badge_plus
person_crop_circle_fill_badge_plus=cupertino/person_crop_circle_fill_badge_plus.png
f752.codepoint=person_crop_circle_fill_badge_xmark
person_crop_circle_fill_badge_xmark=cupertino/person_crop_circle_fill_badge_xmark.png
f753.codepoint=person_crop_rectangle
person_crop_rectangle=cupertino/person_crop_rectangle.png
f754.codepoint=person_crop_rectangle_fill
person_crop_rectangle_fill=cupertino/person_crop_rectangle_fill.png
f755.codepoint=person_crop_square
person_crop_square=cupertino/person_crop_square.png
f756.codepoint=person_crop_square_fill
person_crop_square_fill=cupertino/person_crop_square_fill.png
f47e.codepoint=person_fill
person_fill=cupertino/person_fill.png
# f47e.codepoint=person_solid
person_solid=cupertino/person_solid.png
f757.codepoint=personalhotspot
personalhotspot=cupertino/personalhotspot.png
f758.codepoint=perspective
perspective=cupertino/perspective.png
f4b8.codepoint=phone
phone=cupertino/phone.png
f759.codepoint=phone_arrow_down_left
phone_arrow_down_left=cupertino/phone_arrow_down_left.png
f75a.codepoint=phone_arrow_right
phone_arrow_right=cupertino/phone_arrow_right.png
f75b.codepoint=phone_arrow_up_right
phone_arrow_up_right=cupertino/phone_arrow_up_right.png
f75c.codepoint=phone_badge_plus
phone_badge_plus=cupertino/phone_badge_plus.png
f75d.codepoint=phone_circle
phone_circle=cupertino/phone_circle.png
f75e.codepoint=phone_circle_fill
phone_circle_fill=cupertino/phone_circle_fill.png
f75f.codepoint=phone_down
phone_down=cupertino/phone_down.png
f760.codepoint=phone_down_circle
phone_down_circle=cupertino/phone_down_circle.png
f761.codepoint=phone_down_circle_fill
phone_down_circle_fill=cupertino/phone_down_circle_fill.png
f762.codepoint=phone_down_fill
phone_down_fill=cupertino/phone_down_fill.png
f4b9.codepoint=phone_fill
phone_fill=cupertino/phone_fill.png
f763.codepoint=phone_fill_arrow_down_left
phone_fill_arrow_down_left=cupertino/phone_fill_arrow_down_left.png
f764.codepoint=phone_fill_arrow_right
phone_fill_arrow_right=cupertino/phone_fill_arrow_right.png
f765.codepoint=phone_fill_arrow_up_right
phone_fill_arrow_up_right=cupertino/phone_fill_arrow_up_right.png
f766.codepoint=phone_fill_badge_plus
phone_fill_badge_plus=cupertino/phone_fill_badge_plus.png
# f4b9.codepoint=phone_solid
phone_solid=cupertino/phone_solid.png
f767.codepoint=photo
photo=cupertino/photo.png
# f3f5.codepoint=photo_camera
photo_camera=cupertino/photo_camera.png
# f3f6.codepoint=photo_camera_solid
photo_camera_solid=cupertino/photo_camera_solid.png
f768.codepoint=photo_fill
photo_fill=cupertino/photo_fill.png
f769.codepoint=photo_fill_on_rectangle_fill
photo_fill_on_rectangle_fill=cupertino/photo_fill_on_rectangle_fill.png
f76a.codepoint=photo_on_rectangle
photo_on_rectangle=cupertino/photo_on_rectangle.png
f8ff.codepoint=piano
piano=cupertino/piano.png
f76b.codepoint=pin
pin=cupertino/pin.png
f76c.codepoint=pin_fill
pin_fill=cupertino/pin_fill.png
f76d.codepoint=pin_slash
pin_slash=cupertino/pin_slash.png
f76e.codepoint=pin_slash_fill
pin_slash_fill=cupertino/pin_slash_fill.png
# f455.codepoint=placemark
placemark=cupertino/placemark.png
# f456.codepoint=placemark_fill
placemark_fill=cupertino/placemark_fill.png
f487.codepoint=play
play=cupertino/play.png
# f487.codepoint=play_arrow
play_arrow=cupertino/play_arrow.png
f488.codepoint=play_arrow_solid
play_arrow_solid=cupertino/play_arrow_solid.png
f76f.codepoint=play_circle
play_circle=cupertino/play_circle.png
f770.codepoint=play_circle_fill
play_circle_fill=cupertino/play_circle_fill.png
# f488.codepoint=play_fill
play_fill=cupertino/play_fill.png
f771.codepoint=play_rectangle
play_rectangle=cupertino/play_rectangle.png
f772.codepoint=play_rectangle_fill
play_rectangle_fill=cupertino/play_rectangle_fill.png
f773.codepoint=playpause
playpause=cupertino/playpause.png
f774.codepoint=playpause_fill
playpause_fill=cupertino/playpause_fill.png
# f489.codepoint=plus
plus=cupertino/plus.png
f775.codepoint=plus_app
plus_app=cupertino/plus_app.png
f776.codepoint=plus_app_fill
plus_app_fill=cupertino/plus_app_fill.png
f777.codepoint=plus_bubble
plus_bubble=cupertino/plus_bubble.png
f778.codepoint=plus_bubble_fill
plus_bubble_fill=cupertino/plus_bubble_fill.png
# f48a.codepoint=plus_circle
plus_circle=cupertino/plus_circle.png
# f48b.codepoint=plus_circle_fill
plus_circle_fill=cupertino/plus_circle_fill.png
# f48a.codepoint=plus_circled
plus_circled=cupertino/plus_circled.png
f779.codepoint=plus_rectangle
plus_rectangle=cupertino/plus_rectangle.png
f77a.codepoint=plus_rectangle_fill
plus_rectangle_fill=cupertino/plus_rectangle_fill.png
f77b.codepoint=plus_rectangle_fill_on_rectangle_fill
plus_rectangle_fill_on_rectangle_fill=cupertino/plus_rectangle_fill_on_rectangle_fill.png
f77c.codepoint=plus_rectangle_on_rectangle
plus_rectangle_on_rectangle=cupertino/plus_rectangle_on_rectangle.png
f77d.codepoint=plus_slash_minus
plus_slash_minus=cupertino/plus_slash_minus.png
f77e.codepoint=plus_square
plus_square=cupertino/plus_square.png
f77f.codepoint=plus_square_fill
plus_square_fill=cupertino/plus_square_fill.png
f780.codepoint=plus_square_fill_on_square_fill
plus_square_fill_on_square_fill=cupertino/plus_square_fill_on_square_fill.png
f781.codepoint=plus_square_on_square
plus_square_on_square=cupertino/plus_square_on_square.png
f782.codepoint=plusminus
plusminus=cupertino/plusminus.png
f783.codepoint=plusminus_circle
plusminus_circle=cupertino/plusminus_circle.png
f784.codepoint=plusminus_circle_fill
plusminus_circle_fill=cupertino/plusminus_circle_fill.png
f785.codepoint=power
power=cupertino/power.png
f786.codepoint=printer
printer=cupertino/printer.png
f787.codepoint=printer_fill
printer_fill=cupertino/printer_fill.png
# f419.codepoint=profile_circled
profile_circled=cupertino/profile_circled.png
f788.codepoint=projective
projective=cupertino/projective.png
f789.codepoint=purchased
purchased=cupertino/purchased.png
f78a.codepoint=purchased_circle
purchased_circle=cupertino/purchased_circle.png
f78b.codepoint=purchased_circle_fill
purchased_circle_fill=cupertino/purchased_circle_fill.png
f78c.codepoint=qrcode
qrcode=cupertino/qrcode.png
f78d.codepoint=qrcode_viewfinder
qrcode_viewfinder=cupertino/qrcode_viewfinder.png
f78e.codepoint=question
question=cupertino/question.png
f78f.codepoint=question_circle
question_circle=cupertino/question_circle.png
f790.codepoint=question_circle_fill
question_circle_fill=cupertino/question_circle_fill.png
f791.codepoint=question_diamond
question_diamond=cupertino/question_diamond.png
f792.codepoint=question_diamond_fill
question_diamond_fill=cupertino/question_diamond_fill.png
f793.codepoint=question_square
question_square=cupertino/question_square.png
f794.codepoint=question_square_fill
question_square_fill=cupertino/question_square_fill.png
f795.codepoint=quote_bubble
quote_bubble=cupertino/quote_bubble.png
f796.codepoint=quote_bubble_fill
quote_bubble_fill=cupertino/quote_bubble_fill.png
f797.codepoint=radiowaves_left
radiowaves_left=cupertino/radiowaves_left.png
f798.codepoint=radiowaves_right
radiowaves_right=cupertino/radiowaves_right.png
f799.codepoint=rays
rays=cupertino/rays.png
f79a.codepoint=recordingtape
recordingtape=cupertino/recordingtape.png
f79b.codepoint=rectangle
rectangle=cupertino/rectangle.png
f79c.codepoint=rectangle_3_offgrid
rectangle_3_offgrid=cupertino/rectangle_3_offgrid.png
f79d.codepoint=rectangle_3_offgrid_fill
rectangle_3_offgrid_fill=cupertino/rectangle_3_offgrid_fill.png
f79e.codepoint=rectangle_arrow_up_right_arrow_down_left
rectangle_arrow_up_right_arrow_down_left=cupertino/rectangle_arrow_up_right_arrow_down_left.png
f79f.codepoint=rectangle_arrow_up_right_arrow_down_left_slash
rectangle_arrow_up_right_arrow_down_left_slash=cupertino/rectangle_arrow_up_right_arrow_down_left_slash.png
f7a0.codepoint=rectangle_badge_checkmark
rectangle_badge_checkmark=cupertino/rectangle_badge_checkmark.png
f7a1.codepoint=rectangle_badge_xmark
rectangle_badge_xmark=cupertino/rectangle_badge_xmark.png
f7a2.codepoint=rectangle_compress_vertical
rectangle_compress_vertical=cupertino/rectangle_compress_vertical.png
f7a3.codepoint=rectangle_dock
rectangle_dock=cupertino/rectangle_dock.png
f7a4.codepoint=rectangle_expand_vertical
rectangle_expand_vertical=cupertino/rectangle_expand_vertical.png
f7a5.codepoint=rectangle_fill
rectangle_fill=cupertino/rectangle_fill.png
f7a6.codepoint=rectangle_fill_badge_checkmark
rectangle_fill_badge_checkmark=cupertino/rectangle_fill_badge_checkmark.png
f7a7.codepoint=rectangle_fill_badge_xmark
rectangle_fill_badge_xmark=cupertino/rectangle_fill_badge_xmark.png
f7a8.codepoint=rectangle_fill_on_rectangle_angled_fill
rectangle_fill_on_rectangle_angled_fill=cupertino/rectangle_fill_on_rectangle_angled_fill.png
f7a9.codepoint=rectangle_fill_on_rectangle_fill
rectangle_fill_on_rectangle_fill=cupertino/rectangle_fill_on_rectangle_fill.png
f7aa.codepoint=rectangle_grid_1x2
rectangle_grid_1x2=cupertino/rectangle_grid_1x2.png
f7ab.codepoint=rectangle_grid_1x2_fill
rectangle_grid_1x2_fill=cupertino/rectangle_grid_1x2_fill.png
f7ac.codepoint=rectangle_grid_2x2
rectangle_grid_2x2=cupertino/rectangle_grid_2x2.png
f7ad.codepoint=rectangle_grid_2x2_fill
rectangle_grid_2x2_fill=cupertino/rectangle_grid_2x2_fill.png
f7ae.codepoint=rectangle_grid_3x2
rectangle_grid_3x2=cupertino/rectangle_grid_3x2.png
f7af.codepoint=rectangle_grid_3x2_fill
rectangle_grid_3x2_fill=cupertino/rectangle_grid_3x2_fill.png
f7b0.codepoint=rectangle_on_rectangle
rectangle_on_rectangle=cupertino/rectangle_on_rectangle.png
f7b1.codepoint=rectangle_on_rectangle_angled
rectangle_on_rectangle_angled=cupertino/rectangle_on_rectangle_angled.png
f7b2.codepoint=rectangle_paperclip
rectangle_paperclip=cupertino/rectangle_paperclip.png
f7b3.codepoint=rectangle_split_3x1
rectangle_split_3x1=cupertino/rectangle_split_3x1.png
f7b4.codepoint=rectangle_split_3x1_fill
rectangle_split_3x1_fill=cupertino/rectangle_split_3x1_fill.png
f7b5.codepoint=rectangle_split_3x3
rectangle_split_3x3=cupertino/rectangle_split_3x3.png
f7b6.codepoint=rectangle_split_3x3_fill
rectangle_split_3x3_fill=cupertino/rectangle_split_3x3_fill.png
# f3c9.codepoint=rectangle_stack
rectangle_stack=cupertino/rectangle_stack.png
f7b7.codepoint=rectangle_stack_badge_minus
rectangle_stack_badge_minus=cupertino/rectangle_stack_badge_minus.png
f7b8.codepoint=rectangle_stack_badge_person_crop
rectangle_stack_badge_person_crop=cupertino/rectangle_stack_badge_person_crop.png
f7b9.codepoint=rectangle_stack_badge_plus
rectangle_stack_badge_plus=cupertino/rectangle_stack_badge_plus.png
# f3ca.codepoint=rectangle_stack_fill
rectangle_stack_fill=cupertino/rectangle_stack_fill.png
f7ba.codepoint=rectangle_stack_fill_badge_minus
rectangle_stack_fill_badge_minus=cupertino/rectangle_stack_fill_badge_minus.png
f7bb.codepoint=rectangle_stack_fill_badge_person_crop
rectangle_stack_fill_badge_person_crop=cupertino/rectangle_stack_fill_badge_person_crop.png
f7bc.codepoint=rectangle_stack_fill_badge_plus
rectangle_stack_fill_badge_plus=cupertino/rectangle_stack_fill_badge_plus.png
f7bd.codepoint=rectangle_stack_person_crop
rectangle_stack_person_crop=cupertino/rectangle_stack_person_crop.png
f7be.codepoint=rectangle_stack_person_crop_fill
rectangle_stack_person_crop_fill=cupertino/rectangle_stack_person_crop_fill.png
# f49a.codepoint=refresh
refresh=cupertino/refresh.png
# f21c.codepoint=refresh_bold
refresh_bold=cupertino/refresh_bold.png
# f49b.codepoint=refresh_circled
refresh_circled=cupertino/refresh_circled.png
# f49c.codepoint=refresh_circled_solid
refresh_circled_solid=cupertino/refresh_circled_solid.png
f3a8.codepoint=refresh_thick
refresh_thick=cupertino/refresh_thick.png
f49d.codepoint=refresh_thin
refresh_thin=cupertino/refresh_thin.png
f7bf.codepoint=repeat
repeat=cupertino/repeat.png
f7c0.codepoint=repeat_1
repeat_1=cupertino/repeat_1.png
# f4c6.codepoint=reply
reply=cupertino/reply.png
# f21d.codepoint=reply_all
reply_all=cupertino/reply_all.png
# f21e.codepoint=reply_thick_solid
reply_thick_solid=cupertino/reply_thick_solid.png
f900.codepoint=resize
resize=cupertino/resize.png
f901.codepoint=resize_h
resize_h=cupertino/resize_h.png
f902.codepoint=resize_v
resize_v=cupertino/resize_v.png
# f21c.codepoint=restart
restart=cupertino/restart.png
f7c1.codepoint=return_icon
return_icon=cupertino/return_icon.png
f7c2.codepoint=rhombus
rhombus=cupertino/rhombus.png
f7c3.codepoint=rhombus_fill
rhombus_fill=cupertino/rhombus_fill.png
# f3d3.codepoint=right_chevron
right_chevron=cupertino/right_chevron.png
f903.codepoint=rocket
rocket=cupertino/rocket.png
f904.codepoint=rocket_fill
rocket_fill=cupertino/rocket_fill.png
f7c4.codepoint=rosette
rosette=cupertino/rosette.png
f7c5.codepoint=rotate_left
rotate_left=cupertino/rotate_left.png
f7c6.codepoint=rotate_left_fill
rotate_left_fill=cupertino/rotate_left_fill.png
f7c7.codepoint=rotate_right
rotate_right=cupertino/rotate_right.png
f7c8.codepoint=rotate_right_fill
rotate_right_fill=cupertino/rotate_right_fill.png
f7c9.codepoint=scissors
scissors=cupertino/scissors.png
f905.codepoint=scissors_alt
scissors_alt=cupertino/scissors_alt.png
f7ca.codepoint=scope
scope=cupertino/scope.png
f7cb.codepoint=scribble
scribble=cupertino/scribble.png
f4a5.codepoint=search
search=cupertino/search.png
f7cc.codepoint=search_circle
search_circle=cupertino/search_circle.png
f7cd.codepoint=search_circle_fill
search_circle_fill=cupertino/search_circle_fill.png
f7ce.codepoint=selection_pin_in_out
selection_pin_in_out=cupertino/selection_pin_in_out.png
f411.codepoint=settings
settings=cupertino/settings.png
f412.codepoint=settings_solid
settings_solid=cupertino/settings_solid.png
f4ca.codepoint=share
share=cupertino/share.png
f4cb.codepoint=share_solid
share_solid=cupertino/share_solid.png
f220.codepoint=share_up
share_up=cupertino/share_up.png
f7cf.codepoint=shield
shield=cupertino/shield.png
f7d0.codepoint=shield_fill
shield_fill=cupertino/shield_fill.png
f7d1.codepoint=shield_lefthalf_fill
shield_lefthalf_fill=cupertino/shield_lefthalf_fill.png
f7d2.codepoint=shield_slash
shield_slash=cupertino/shield_slash.png
f7d3.codepoint=shield_slash_fill
shield_slash_fill=cupertino/shield_slash_fill.png
f7d4.codepoint=shift
shift=cupertino/shift.png
f7d5.codepoint=shift_fill
shift_fill=cupertino/shift_fill.png
# f3f7.codepoint=shopping_cart
shopping_cart=cupertino/shopping_cart.png
f4a9.codepoint=shuffle
shuffle=cupertino/shuffle.png
f4a8.codepoint=shuffle_medium
shuffle_medium=cupertino/shuffle_medium.png
f221.codepoint=shuffle_thick
shuffle_thick=cupertino/shuffle_thick.png
f7d6.codepoint=sidebar_left
sidebar_left=cupertino/sidebar_left.png
f7d7.codepoint=sidebar_right
sidebar_right=cupertino/sidebar_right.png
f7d8.codepoint=signature
signature=cupertino/signature.png
f7d9.codepoint=skew
skew=cupertino/skew.png
f7da.codepoint=slash_circle
slash_circle=cupertino/slash_circle.png
f7db.codepoint=slash_circle_fill
slash_circle_fill=cupertino/slash_circle_fill.png
f7dc.codepoint=slider_horizontal_3
slider_horizontal_3=cupertino/slider_horizontal_3.png
f7dd.codepoint=slider_horizontal_below_rectangle
slider_horizontal_below_rectangle=cupertino/slider_horizontal_below_rectangle.png
f7de.codepoint=slowmo
slowmo=cupertino/slowmo.png
f7df.codepoint=smallcircle_circle
smallcircle_circle=cupertino/smallcircle_circle.png
f7e0.codepoint=smallcircle_circle_fill
smallcircle_circle_fill=cupertino/smallcircle_circle_fill.png
f7e1.codepoint=smallcircle_fill_circle
smallcircle_fill_circle=cupertino/smallcircle_fill_circle.png
f7e2.codepoint=smallcircle_fill_circle_fill
smallcircle_fill_circle_fill=cupertino/smallcircle_fill_circle_fill.png
f7e3.codepoint=smiley
smiley=cupertino/smiley.png
f7e4.codepoint=smiley_fill
smiley_fill=cupertino/smiley_fill.png
f7e5.codepoint=smoke
smoke=cupertino/smoke.png
f7e6.codepoint=smoke_fill
smoke_fill=cupertino/smoke_fill.png
f7e7.codepoint=snow
snow=cupertino/snow.png
f906.codepoint=sort_down
sort_down=cupertino/sort_down.png
f907.codepoint=sort_down_circle
sort_down_circle=cupertino/sort_down_circle.png
f908.codepoint=sort_down_circle_fill
sort_down_circle_fill=cupertino/sort_down_circle_fill.png
f909.codepoint=sort_up
sort_up=cupertino/sort_up.png
f90a.codepoint=sort_up_circle
sort_up_circle=cupertino/sort_up_circle.png
f90b.codepoint=sort_up_circle_fill
sort_up_circle_fill=cupertino/sort_up_circle_fill.png
f7e8.codepoint=sparkles
sparkles=cupertino/sparkles.png
f7e9.codepoint=speaker
speaker=cupertino/speaker.png
f7ea.codepoint=speaker_1
speaker_1=cupertino/speaker_1.png
f3b7.codepoint=speaker_1_fill
speaker_1_fill=cupertino/speaker_1_fill.png
f7eb.codepoint=speaker_2
speaker_2=cupertino/speaker_2.png
f7ec.codepoint=speaker_2_fill
speaker_2_fill=cupertino/speaker_2_fill.png
f7ed.codepoint=speaker_3
speaker_3=cupertino/speaker_3.png
f3ba.codepoint=speaker_3_fill
speaker_3_fill=cupertino/speaker_3_fill.png
f3b8.codepoint=speaker_fill
speaker_fill=cupertino/speaker_fill.png
f7ee.codepoint=speaker_slash
speaker_slash=cupertino/speaker_slash.png
f3b9.codepoint=speaker_slash_fill
speaker_slash_fill=cupertino/speaker_slash_fill.png
f7ef.codepoint=speaker_slash_fill_rtl
speaker_slash_fill_rtl=cupertino/speaker_slash_fill_rtl.png
f7f0.codepoint=speaker_slash_rtl
speaker_slash_rtl=cupertino/speaker_slash_rtl.png
f7f1.codepoint=speaker_zzz
speaker_zzz=cupertino/speaker_zzz.png
f7f2.codepoint=speaker_zzz_fill
speaker_zzz_fill=cupertino/speaker_zzz_fill.png
f7f3.codepoint=speaker_zzz_fill_rtl
speaker_zzz_fill_rtl=cupertino/speaker_zzz_fill_rtl.png
f7f4.codepoint=speaker_zzz_rtl
speaker_zzz_rtl=cupertino/speaker_zzz_rtl.png
f7f5.codepoint=speedometer
speedometer=cupertino/speedometer.png
f7f6.codepoint=sportscourt
sportscourt=cupertino/sportscourt.png
f7f7.codepoint=sportscourt_fill
sportscourt_fill=cupertino/sportscourt_fill.png
f7f8.codepoint=square
square=cupertino/square.png
f7f9.codepoint=square_arrow_down
square_arrow_down=cupertino/square_arrow_down.png
f7fa.codepoint=square_arrow_down_fill
square_arrow_down_fill=cupertino/square_arrow_down_fill.png
f7fb.codepoint=square_arrow_down_on_square
square_arrow_down_on_square=cupertino/square_arrow_down_on_square.png
f7fc.codepoint=square_arrow_down_on_square_fill
square_arrow_down_on_square_fill=cupertino/square_arrow_down_on_square_fill.png
f90c.codepoint=square_arrow_left
square_arrow_left=cupertino/square_arrow_left.png
f90d.codepoint=square_arrow_left_fill
square_arrow_left_fill=cupertino/square_arrow_left_fill.png
f90e.codepoint=square_arrow_right
square_arrow_right=cupertino/square_arrow_right.png
f90f.codepoint=square_arrow_right_fill
square_arrow_right_fill=cupertino/square_arrow_right_fill.png
# f4ca.codepoint=square_arrow_up
square_arrow_up=cupertino/square_arrow_up.png
# f4cb.codepoint=square_arrow_up_fill
square_arrow_up_fill=cupertino/square_arrow_up_fill.png
f7fd.codepoint=square_arrow_up_on_square
square_arrow_up_on_square=cupertino/square_arrow_up_on_square.png
f7fe.codepoint=square_arrow_up_on_square_fill
square_arrow_up_on_square_fill=cupertino/square_arrow_up_on_square_fill.png
f910.codepoint=square_favorites
square_favorites=cupertino/square_favorites.png
f911.codepoint=square_favorites_alt
square_favorites_alt=cupertino/square_favorites_alt.png
f912.codepoint=square_favorites_alt_fill
square_favorites_alt_fill=cupertino/square_favorites_alt_fill.png
f913.codepoint=square_favorites_fill
square_favorites_fill=cupertino/square_favorites_fill.png
f7ff.codepoint=square_fill
square_fill=cupertino/square_fill.png
f800.codepoint=square_fill_line_vertical_square
square_fill_line_vertical_square=cupertino/square_fill_line_vertical_square.png
f801.codepoint=square_fill_line_vertical_square_fill
square_fill_line_vertical_square_fill=cupertino/square_fill_line_vertical_square_fill.png
f802.codepoint=square_fill_on_circle_fill
square_fill_on_circle_fill=cupertino/square_fill_on_circle_fill.png
f803.codepoint=square_fill_on_square_fill
square_fill_on_square_fill=cupertino/square_fill_on_square_fill.png
f804.codepoint=square_grid_2x2
square_grid_2x2=cupertino/square_grid_2x2.png
f805.codepoint=square_grid_2x2_fill
square_grid_2x2_fill=cupertino/square_grid_2x2_fill.png
f806.codepoint=square_grid_3x2
square_grid_3x2=cupertino/square_grid_3x2.png
f807.codepoint=square_grid_3x2_fill
square_grid_3x2_fill=cupertino/square_grid_3x2_fill.png
f808.codepoint=square_grid_4x3_fill
square_grid_4x3_fill=cupertino/square_grid_4x3_fill.png
f809.codepoint=square_lefthalf_fill
square_lefthalf_fill=cupertino/square_lefthalf_fill.png
f80a.codepoint=square_line_vertical_square
square_line_vertical_square=cupertino/square_line_vertical_square.png
f80b.codepoint=square_line_vertical_square_fill
square_line_vertical_square_fill=cupertino/square_line_vertical_square_fill.png
f914.codepoint=square_list
square_list=cupertino/square_list.png
f915.codepoint=square_list_fill
square_list_fill=cupertino/square_list_fill.png
f80c.codepoint=square_on_circle
square_on_circle=cupertino/square_on_circle.png
f80d.codepoint=square_on_square
square_on_square=cupertino/square_on_square.png
# f417.codepoint=square_pencil
square_pencil=cupertino/square_pencil.png
# f417.codepoint=square_pencil_fill
square_pencil_fill=cupertino/square_pencil_fill.png
f80e.codepoint=square_righthalf_fill
square_righthalf_fill=cupertino/square_righthalf_fill.png
f80f.codepoint=square_split_1x2
square_split_1x2=cupertino/square_split_1x2.png
f810.codepoint=square_split_1x2_fill
square_split_1x2_fill=cupertino/square_split_1x2_fill.png
f811.codepoint=square_split_2x1
square_split_2x1=cupertino/square_split_2x1.png
f812.codepoint=square_split_2x1_fill
square_split_2x1_fill=cupertino/square_split_2x1_fill.png
f813.codepoint=square_split_2x2
square_split_2x2=cupertino/square_split_2x2.png
f814.codepoint=square_split_2x2_fill
square_split_2x2_fill=cupertino/square_split_2x2_fill.png
f815.codepoint=square_stack
square_stack=cupertino/square_stack.png
f816.codepoint=square_stack_3d_down_dottedline
square_stack_3d_down_dottedline=cupertino/square_stack_3d_down_dottedline.png
f817.codepoint=square_stack_3d_down_right
square_stack_3d_down_right=cupertino/square_stack_3d_down_right.png
f818.codepoint=square_stack_3d_down_right_fill
square_stack_3d_down_right_fill=cupertino/square_stack_3d_down_right_fill.png
f819.codepoint=square_stack_3d_up
square_stack_3d_up=cupertino/square_stack_3d_up.png
f81a.codepoint=square_stack_3d_up_fill
square_stack_3d_up_fill=cupertino/square_stack_3d_up_fill.png
f81b.codepoint=square_stack_3d_up_slash
square_stack_3d_up_slash=cupertino/square_stack_3d_up_slash.png
f81c.codepoint=square_stack_3d_up_slash_fill
square_stack_3d_up_slash_fill=cupertino/square_stack_3d_up_slash_fill.png
f81d.codepoint=square_stack_fill
square_stack_fill=cupertino/square_stack_fill.png
f81e.codepoint=squares_below_rectangle
squares_below_rectangle=cupertino/squares_below_rectangle.png
f81f.codepoint=star
star=cupertino/star.png
f820.codepoint=star_circle
star_circle=cupertino/star_circle.png
f821.codepoint=star_circle_fill
star_circle_fill=cupertino/star_circle_fill.png
f822.codepoint=star_fill
star_fill=cupertino/star_fill.png
f823.codepoint=star_lefthalf_fill
star_lefthalf_fill=cupertino/star_lefthalf_fill.png
f824.codepoint=star_slash
star_slash=cupertino/star_slash.png
f825.codepoint=star_slash_fill
star_slash_fill=cupertino/star_slash_fill.png
f826.codepoint=staroflife
staroflife=cupertino/staroflife.png
f827.codepoint=staroflife_fill
staroflife_fill=cupertino/staroflife_fill.png
f828.codepoint=stop
stop=cupertino/stop.png
f829.codepoint=stop_circle
stop_circle=cupertino/stop_circle.png
f82a.codepoint=stop_circle_fill
stop_circle_fill=cupertino/stop_circle_fill.png
f82b.codepoint=stop_fill
stop_fill=cupertino/stop_fill.png
f82c.codepoint=stopwatch
stopwatch=cupertino/stopwatch.png
f82d.codepoint=stopwatch_fill
stopwatch_fill=cupertino/stopwatch_fill.png
f82e.codepoint=strikethrough
strikethrough=cupertino/strikethrough.png
f82f.codepoint=suit_club
suit_club=cupertino/suit_club.png
f830.codepoint=suit_club_fill
suit_club_fill=cupertino/suit_club_fill.png
f831.codepoint=suit_diamond
suit_diamond=cupertino/suit_diamond.png
f832.codepoint=suit_diamond_fill
suit_diamond_fill=cupertino/suit_diamond_fill.png
f833.codepoint=suit_heart
suit_heart=cupertino/suit_heart.png
f834.codepoint=suit_heart_fill
suit_heart_fill=cupertino/suit_heart_fill.png
f835.codepoint=suit_spade
suit_spade=cupertino/suit_spade.png
f836.codepoint=suit_spade_fill
suit_spade_fill=cupertino/suit_spade_fill.png
f837.codepoint=sum
sum=cupertino/sum.png
f838.codepoint=sun_dust
sun_dust=cupertino/sun_dust.png
f839.codepoint=sun_dust_fill
sun_dust_fill=cupertino/sun_dust_fill.png
f83a.codepoint=sun_haze
sun_haze=cupertino/sun_haze.png
f83b.codepoint=sun_haze_fill
sun_haze_fill=cupertino/sun_haze_fill.png
# f4b6.codepoint=sun_max
sun_max=cupertino/sun_max.png
# f4b7.codepoint=sun_max_fill
sun_max_fill=cupertino/sun_max_fill.png
f83c.codepoint=sun_min
sun_min=cupertino/sun_min.png
f83d.codepoint=sun_min_fill
sun_min_fill=cupertino/sun_min_fill.png
f83e.codepoint=sunrise
sunrise=cupertino/sunrise.png
f83f.codepoint=sunrise_fill
sunrise_fill=cupertino/sunrise_fill.png
f840.codepoint=sunset
sunset=cupertino/sunset.png
f841.codepoint=sunset_fill
sunset_fill=cupertino/sunset_fill.png
# f49e.codepoint=switch_camera
switch_camera=cupertino/switch_camera.png
# f49f.codepoint=switch_camera_solid
switch_camera_solid=cupertino/switch_camera_solid.png
f842.codepoint=t_bubble
t_bubble=cupertino/t_bubble.png
f843.codepoint=t_bubble_fill
t_bubble_fill=cupertino/t_bubble_fill.png
f844.codepoint=table
table=cupertino/table.png
f845.codepoint=table_badge_more
table_badge_more=cupertino/table_badge_more.png
f846.codepoint=table_badge_more_fill
table_badge_more_fill=cupertino/table_badge_more_fill.png
f847.codepoint=table_fill
table_fill=cupertino/table_fill.png
f48c.codepoint=tag
tag=cupertino/tag.png
f848.codepoint=tag_circle
tag_circle=cupertino/tag_circle.png
f849.codepoint=tag_circle_fill
tag_circle_fill=cupertino/tag_circle_fill.png
f48d.codepoint=tag_fill
tag_fill=cupertino/tag_fill.png
# f48d.codepoint=tag_solid
tag_solid=cupertino/tag_solid.png
f48e.codepoint=tags
tags=cupertino/tags.png
f48f.codepoint=tags_solid
tags_solid=cupertino/tags_solid.png
f84a.codepoint=text_aligncenter
text_aligncenter=cupertino/text_aligncenter.png
f84b.codepoint=text_alignleft
text_alignleft=cupertino/text_alignleft.png
f84c.codepoint=text_alignright
text_alignright=cupertino/text_alignright.png
f84d.codepoint=text_append
text_append=cupertino/text_append.png
f84e.codepoint=text_badge_checkmark
text_badge_checkmark=cupertino/text_badge_checkmark.png
f84f.codepoint=text_badge_minus
text_badge_minus=cupertino/text_badge_minus.png
f850.codepoint=text_badge_plus
text_badge_plus=cupertino/text_badge_plus.png
f851.codepoint=text_badge_star
text_badge_star=cupertino/text_badge_star.png
f852.codepoint=text_badge_xmark
text_badge_xmark=cupertino/text_badge_xmark.png
f853.codepoint=text_bubble
text_bubble=cupertino/text_bubble.png
f854.codepoint=text_bubble_fill
text_bubble_fill=cupertino/text_bubble_fill.png
f855.codepoint=text_cursor
text_cursor=cupertino/text_cursor.png
f856.codepoint=text_insert
text_insert=cupertino/text_insert.png
f857.codepoint=text_justify
text_justify=cupertino/text_justify.png
f858.codepoint=text_justifyleft
text_justifyleft=cupertino/text_justifyleft.png
f859.codepoint=text_justifyright
text_justifyright=cupertino/text_justifyright.png
f85a.codepoint=text_quote
text_quote=cupertino/text_quote.png
f85b.codepoint=textbox
textbox=cupertino/textbox.png
f85c.codepoint=textformat
textformat=cupertino/textformat.png
f85d.codepoint=textformat_123
textformat_123=cupertino/textformat_123.png
f85e.codepoint=textformat_abc
textformat_abc=cupertino/textformat_abc.png
f85f.codepoint=textformat_abc_dottedunderline
textformat_abc_dottedunderline=cupertino/textformat_abc_dottedunderline.png
f860.codepoint=textformat_alt
textformat_alt=cupertino/textformat_alt.png
f861.codepoint=textformat_size
textformat_size=cupertino/textformat_size.png
f862.codepoint=textformat_subscript
textformat_subscript=cupertino/textformat_subscript.png
f863.codepoint=textformat_superscript
textformat_superscript=cupertino/textformat_superscript.png
f864.codepoint=thermometer
thermometer=cupertino/thermometer.png
f865.codepoint=thermometer_snowflake
thermometer_snowflake=cupertino/thermometer_snowflake.png
f866.codepoint=thermometer_sun
thermometer_sun=cupertino/thermometer_sun.png
f916.codepoint=ticket
ticket=cupertino/ticket.png
f917.codepoint=ticket_fill
ticket_fill=cupertino/ticket_fill.png
f918.codepoint=tickets
tickets=cupertino/tickets.png
f919.codepoint=tickets_fill
tickets_fill=cupertino/tickets_fill.png
f402.codepoint=time
time=cupertino/time.png
# f403.codepoint=time_solid
time_solid=cupertino/time_solid.png
f867.codepoint=timelapse
timelapse=cupertino/timelapse.png
f868.codepoint=timer
timer=cupertino/timer.png
f91a.codepoint=timer_fill
timer_fill=cupertino/timer_fill.png
f91b.codepoint=today
today=cupertino/today.png
f91c.codepoint=today_fill
today_fill=cupertino/today_fill.png
f869.codepoint=tornado
tornado=cupertino/tornado.png
f86a.codepoint=tortoise
tortoise=cupertino/tortoise.png
f86b.codepoint=tortoise_fill
tortoise_fill=cupertino/tortoise_fill.png
f3af.codepoint=train_style_one
train_style_one=cupertino/train_style_one.png
f3b4.codepoint=train_style_two
train_style_two=cupertino/train_style_two.png
f86c.codepoint=tram_fill
tram_fill=cupertino/tram_fill.png
# f4c4.codepoint=trash
trash=cupertino/trash.png
f86d.codepoint=trash_circle
trash_circle=cupertino/trash_circle.png
f86e.codepoint=trash_circle_fill
trash_circle_fill=cupertino/trash_circle_fill.png
# f4c5.codepoint=trash_fill
trash_fill=cupertino/trash_fill.png
f86f.codepoint=trash_slash
trash_slash=cupertino/trash_slash.png
f870.codepoint=trash_slash_fill
trash_slash_fill=cupertino/trash_slash_fill.png
f871.codepoint=tray
tray=cupertino/tray.png
f872.codepoint=tray_2
tray_2=cupertino/tray_2.png
f873.codepoint=tray_2_fill
tray_2_fill=cupertino/tray_2_fill.png
f874.codepoint=tray_arrow_down
tray_arrow_down=cupertino/tray_arrow_down.png
f875.codepoint=tray_arrow_down_fill
tray_arrow_down_fill=cupertino/tray_arrow_down_fill.png
f876.codepoint=tray_arrow_up
tray_arrow_up=cupertino/tray_arrow_up.png
f877.codepoint=tray_arrow_up_fill
tray_arrow_up_fill=cupertino/tray_arrow_up_fill.png
f878.codepoint=tray_fill
tray_fill=cupertino/tray_fill.png
f879.codepoint=tray_full
tray_full=cupertino/tray_full.png
f87a.codepoint=tray_full_fill
tray_full_fill=cupertino/tray_full_fill.png
f91d.codepoint=tree
tree=cupertino/tree.png
f87b.codepoint=triangle
triangle=cupertino/triangle.png
f87c.codepoint=triangle_fill
triangle_fill=cupertino/triangle_fill.png
f87d.codepoint=triangle_lefthalf_fill
triangle_lefthalf_fill=cupertino/triangle_lefthalf_fill.png
f87e.codepoint=triangle_righthalf_fill
triangle_righthalf_fill=cupertino/triangle_righthalf_fill.png
f87f.codepoint=tropicalstorm
tropicalstorm=cupertino/tropicalstorm.png
f880.codepoint=tuningfork
tuningfork=cupertino/tuningfork.png
f881.codepoint=tv
tv=cupertino/tv.png
f882.codepoint=tv_circle
tv_circle=cupertino/tv_circle.png
f883.codepoint=tv_circle_fill
tv_circle_fill=cupertino/tv_circle_fill.png
f884.codepoint=tv_fill
tv_fill=cupertino/tv_fill.png
f885.codepoint=tv_music_note
tv_music_note=cupertino/tv_music_note.png
f886.codepoint=tv_music_note_fill
tv_music_note_fill=cupertino/tv_music_note_fill.png
f887.codepoint=uiwindow_split_2x1
uiwindow_split_2x1=cupertino/uiwindow_split_2x1.png
f888.codepoint=umbrella
umbrella=cupertino/umbrella.png
f889.codepoint=umbrella_fill
umbrella_fill=cupertino/umbrella_fill.png
f88a.codepoint=underline
underline=cupertino/underline.png
# f366.codepoint=up_arrow
up_arrow=cupertino/up_arrow.png
f91e.codepoint=upload_circle
upload_circle=cupertino/upload_circle.png
f91f.codepoint=upload_circle_fill
upload_circle_fill=cupertino/upload_circle_fill.png
f4cc.codepoint=video_camera
video_camera=cupertino/video_camera.png
f4cd.codepoint=video_camera_solid
video_camera_solid=cupertino/video_camera_solid.png
# f4cc.codepoint=videocam
videocam=cupertino/videocam.png
f920.codepoint=videocam_circle
videocam_circle=cupertino/videocam_circle.png
f921.codepoint=videocam_circle_fill
videocam_circle_fill=cupertino/videocam_circle_fill.png
# f4cd.codepoint=videocam_fill
videocam_fill=cupertino/videocam_fill.png
f88b.codepoint=view_2d
view_2d=cupertino/view_2d.png
f88c.codepoint=view_3d
view_3d=cupertino/view_3d.png
f88d.codepoint=viewfinder
viewfinder=cupertino/viewfinder.png
f88e.codepoint=viewfinder_circle
viewfinder_circle=cupertino/viewfinder_circle.png
f88f.codepoint=viewfinder_circle_fill
viewfinder_circle_fill=cupertino/viewfinder_circle_fill.png
# f3b7.codepoint=volume_down
volume_down=cupertino/volume_down.png
# f3b8.codepoint=volume_mute
volume_mute=cupertino/volume_mute.png
# f3b9.codepoint=volume_off
volume_off=cupertino/volume_off.png
# f3ba.codepoint=volume_up
volume_up=cupertino/volume_up.png
f890.codepoint=wand_rays
wand_rays=cupertino/wand_rays.png
f891.codepoint=wand_rays_inverse
wand_rays_inverse=cupertino/wand_rays_inverse.png
f892.codepoint=wand_stars
wand_stars=cupertino/wand_stars.png
f893.codepoint=wand_stars_inverse
wand_stars_inverse=cupertino/wand_stars_inverse.png
f894.codepoint=waveform
waveform=cupertino/waveform.png
f895.codepoint=waveform_circle
waveform_circle=cupertino/waveform_circle.png
f896.codepoint=waveform_circle_fill
waveform_circle_fill=cupertino/waveform_circle_fill.png
f897.codepoint=waveform_path
waveform_path=cupertino/waveform_path.png
f898.codepoint=waveform_path_badge_minus
waveform_path_badge_minus=cupertino/waveform_path_badge_minus.png
f899.codepoint=waveform_path_badge_plus
waveform_path_badge_plus=cupertino/waveform_path_badge_plus.png
f89a.codepoint=waveform_path_ecg
waveform_path_ecg=cupertino/waveform_path_ecg.png
f89b.codepoint=wifi
wifi=cupertino/wifi.png
f89c.codepoint=wifi_exclamationmark
wifi_exclamationmark=cupertino/wifi_exclamationmark.png
f89d.codepoint=wifi_slash
wifi_slash=cupertino/wifi_slash.png
f89e.codepoint=wind
wind=cupertino/wind.png
f89f.codepoint=wind_snow
wind_snow=cupertino/wind_snow.png
f8a0.codepoint=wrench
wrench=cupertino/wrench.png
f8a1.codepoint=wrench_fill
wrench_fill=cupertino/wrench_fill.png
# f404.codepoint=xmark
xmark=cupertino/xmark.png
# f405.codepoint=xmark_circle
xmark_circle=cupertino/xmark_circle.png
# f36e.codepoint=xmark_circle_fill
xmark_circle_fill=cupertino/xmark_circle_fill.png
f8a2.codepoint=xmark_octagon
xmark_octagon=cupertino/xmark_octagon.png
f8a3.codepoint=xmark_octagon_fill
xmark_octagon_fill=cupertino/xmark_octagon_fill.png
f8a4.codepoint=xmark_rectangle
xmark_rectangle=cupertino/xmark_rectangle.png
f8a5.codepoint=xmark_rectangle_fill
xmark_rectangle_fill=cupertino/xmark_rectangle_fill.png
f8a6.codepoint=xmark_seal
xmark_seal=cupertino/xmark_seal.png
f8a7.codepoint=xmark_seal_fill
xmark_seal_fill=cupertino/xmark_seal_fill.png
f8a8.codepoint=xmark_shield
xmark_shield=cupertino/xmark_shield.png
f8a9.codepoint=xmark_shield_fill
xmark_shield_fill=cupertino/xmark_shield_fill.png
f8aa.codepoint=xmark_square
xmark_square=cupertino/xmark_square.png
f8ab.codepoint=xmark_square_fill
xmark_square_fill=cupertino/xmark_square_fill.png
f8ac.codepoint=zoom_in
zoom_in=cupertino/zoom_in.png
f8ad.codepoint=zoom_out
zoom_out=cupertino/zoom_out.png
f8ae.codepoint=zzz
zzz=cupertino/zzz.png | flutter-intellij/flutter-idea/testData/utils/cupertino.properties/0 | {
"file_path": "flutter-intellij/flutter-idea/testData/utils/cupertino.properties",
"repo_id": "flutter-intellij",
"token_count": 44076
} | 516 |
/*
* Copyright 2019 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.
*/
package io.flutter.console;
import com.intellij.execution.filters.Filter;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.TestDir;
import io.flutter.testing.Testing;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class FlutterConsoleFilterTest {
@ClassRule
public static final ProjectFixture fixture = Testing.makeEmptyProject();
@ClassRule
public static final TestDir tmp = new TestDir();
static VirtualFile contentRoot;
static String appDir;
@BeforeClass
public static void setUp() throws Exception {
contentRoot = tmp.ensureDir("root");
appDir = tmp.ensureDir("root/test").getPath();
tmp.writeFile("root/test/widget_test.dart", "");
Testing.runOnDispatchThread(
() -> ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath()));
}
@Test @Ignore
public void checkTestFileUrlLink() {
final String line = "#4 main.<anonymous closure> (file://" + appDir + "/widget_test.dart:23:18)\n";
final Filter.Result link = new FlutterConsoleFilter(fixture.getModule()).applyFilter(line, 659);
assertNotNull(link);
}
@Test @Ignore
public void checkLaunchingLink() {
final String line = "Launching test/widget_test.dart on Android SDK built for x86 in debug mode...\n";
final Filter.Result link = new FlutterConsoleFilter(fixture.getModule()).applyFilter(line, line.length());
assertNotNull(link);
}
@Test @Ignore
public void checkErrorMessage() {
final String line = "test/widget_test.dart:23:18: Error: Expected ';' after this.";
final Filter.Result link = new FlutterConsoleFilter(fixture.getModule()).applyFilter(line, line.length());
assertNotNull(link);
}
@Test(timeout=1000) @Ignore
public void checkBadErrorMessage() {
final Filter.Result link = new FlutterConsoleFilter(fixture.getModule()).applyFilter(backtracker, backtracker.length());
assertNull(link);
}
private static final String backtracker =
"export HEADER_SEARCH_PATHS=\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/include"+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/FMDB/FMDB.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/GPUImage/GPUImage.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Mantle/Mantle.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Reachability/Reachability.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Regift/Regift.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/UICKeyChainStore/UICKeyChainStore.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/agora/agora.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/amap_location/amap_location.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/android_intent/android_intent.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/audioplayer2/audioplayer2.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/audioplayers/audioplayers.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/connectivity/connectivity.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/default_plugin/default_plugin.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/device_info/device_info.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/dfa/dfa.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_aliyun_account_certify/flutter_aliyun_account_certify.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_bugly/flutter_bugly.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_drag_scale/flutter_drag_scale.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_image_compress/flutter_image_compress.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_inapp_purchase/flutter_inapp_purchase.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_local_notifications/flutter_local_notifications.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_picker/flutter_picker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_qq/flutter_qq.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_sound/flutter_sound.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_statusbar_manager/flutter_statusbar_manager.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_video_compress/flutter_video_compress.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/fluwx/fluwx.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/image_editor/image_editor.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/image_picker/image_picker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/keyboard_visibility/keyboard_visibility.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/local_auth/local_auth.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/location/location.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/onekey/onekey.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/package_info/package_info.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/path_provider/path_provider.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/permission_handler/permission_handler.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/photo_manager/photo_manager.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/quick_actions/quick_actions.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/rongcloud/rongcloud.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/root_checker/root_checker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/screen/screen.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/sensors/sensors.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/share/share.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/shared_preferences/shared_preferences.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/sqflite/sqflite.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/tracker/tracker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/uni_links/uni_links.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/url_launcher/url_launcher.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/video_player/video_player.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/webview_flutter/webview_flutter.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/FMDB/FMDB.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/GPUImage/GPUImage.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Mantle/Mantle.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Reachability/Reachability.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/Regift/Regift.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/UICKeyChainStore/UICKeyChainStore.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/agora/agora.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/amap_location/amap_location.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/android_intent/android_intent.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/audioplayer2/audioplayer2.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/audioplayers/audioplayers.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/connectivity/connectivity.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/default_plugin/default_plugin.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/device_info/device_info.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/dfa/dfa.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_aliyun_account_certify/flutter_aliyun_account_certify.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_bugly/flutter_bugly.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_drag_scale/flutter_drag_scale.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_image_compress/flutter_image_compress.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_inapp_purchase/flutter_inapp_purchase.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_local_notifications/flutter_local_notifications.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_picker/flutter_picker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_qq/flutter_qq.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_sound/flutter_sound.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_statusbar_manager/flutter_statusbar_manager.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/flutter_video_compress/flutter_video_compress.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/fluwx/fluwx.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/image_editor/image_editor.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/image_picker/image_picker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/keyboard_visibility/keyboard_visibility.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/local_auth/local_auth.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/location/location.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/onekey/onekey.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/package_info/package_info.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/path_provider/path_provider.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/permission_handler/permission_handler.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/photo_manager/photo_manager.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/quick_actions/quick_actions.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/rongcloud/rongcloud.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/root_checker/root_checker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/screen/screen.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/sensors/sensors.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/share/share.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/shared_preferences/shared_preferences.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/sqflite/sqflite.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/tracker/tracker.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/uni_links/uni_links.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/url_launcher/url_launcher.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/video_player/video_player.framework/Headers\""+
"\"/Users/user/workspace/eec/foobar/build/ios/Debug-iphonesimulator/webview_flutter/webview_flutter.framework/Headers\"\"";
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/console/FlutterConsoleFilterTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/console/FlutterConsoleFilterTest.java",
"repo_id": "flutter-intellij",
"token_count": 5572
} | 517 |
{
"type": "Event",
"kind": "Logging",
"isolate": {
"type": "@Isolate",
"id": "isolates/170696135467167",
"name": "main",
"number": "170696135467167"
},
"timestamp": 1562619110758,
"logRecord": {
"type": "LogRecord",
"sequenceNumber": 4,
"time": 1562619110758,
"level": 0,
"loggerName": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/18",
"length": 0,
"valueAsString": ""
},
"message": {
"type": "@Instance",
"_vmType": "String",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/76",
"name": "_OneByteString",
"_vmName": "_OneByteString@0150898"
},
"kind": "String",
"id": "objects/19",
"length": 11,
"valueAsString": "hello world"
},
"zone": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
},
"error": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
},
"stackTrace": {
"type": "@Instance",
"class": {
"type": "@Class",
"fixedId": true,
"id": "classes/141",
"name": "Null"
},
"kind": "Null",
"fixedId": true,
"id": "objects/null",
"valueAsString": "null"
}
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_2.json/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/logging/console_log_2.json",
"repo_id": "flutter-intellij",
"token_count": 985
} | 518 |
/*
* Copyright 2018 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.
*/
package io.flutter.run.bazelTest;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.RuntimeConfigurationError;
import com.intellij.mock.MockVirtualFileSystem;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import io.flutter.bazel.FakeWorkspaceFactory;
import io.flutter.bazel.Workspace;
import io.flutter.run.common.RunMode;
import io.flutter.testing.ProjectFixture;
import io.flutter.testing.Testing;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Rule;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertTrue;
public class LaunchCommandsTest {
@Rule
public ProjectFixture projectFixture = Testing.makeCodeInsightModule();
@Test
public void producesCorrectCommandLineForBazelTarget() throws ExecutionException {
final BazelTestFields fields = forTarget("//foo:test");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("//foo:test");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForBazelTargetWithNoMachineFlag() throws ExecutionException {
final BazelTestFields fields = new FakeBazelTestFields(
BazelTestFields.forTarget("//foo:test", "--no-machine")
);
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-machine");
expectedCommandLine.add("--no-color");
expectedCommandLine.add("//foo:test");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForBazelTargetInDebugMode() throws ExecutionException {
final BazelTestFields fields = forTarget("//foo:test");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.DEBUG);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("//foo:test");
expectedCommandLine.add("--");
expectedCommandLine.add("--enable-debugging");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForFile() throws ExecutionException {
final BazelTestFields fields = forFile("/workspace/foo/test/foo_test.dart");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("foo/test/foo_test.dart");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForFileWithNoMachineFlag() throws ExecutionException {
final BazelTestFields fields = new FakeBazelTestFields(
BazelTestFields.forFile("/workspace/foo/test/foo_test.dart", "--no-machine")
);
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-machine");
expectedCommandLine.add("--no-color");
expectedCommandLine.add("foo/test/foo_test.dart");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForFileInDebugMode() throws ExecutionException {
final BazelTestFields fields = forFile("/workspace/foo/test/foo_test.dart");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.DEBUG);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("foo/test/foo_test.dart");
expectedCommandLine.add("--");
expectedCommandLine.add("--enable-debugging");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForTestName() throws ExecutionException {
final BazelTestFields fields = forTestName("first test", "/workspace/foo/test/foo_test.dart");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("--name");
expectedCommandLine.add("first test");
expectedCommandLine.add("foo/test/foo_test.dart");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForTestNameWithNoMachineFlag() throws ExecutionException {
final BazelTestFields fields = new FakeBazelTestFields(
BazelTestFields.forTestName("first test", "/workspace/foo/test/foo_test.dart", "--no-machine")
);
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-machine");
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--name");
expectedCommandLine.add("first test");
expectedCommandLine.add("foo/test/foo_test.dart");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void producesCorrectCommandLineForTestNameInDebugMode() throws ExecutionException {
final BazelTestFields fields = forTestName("first test", "/workspace/foo/test/foo_test.dart");
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.DEBUG);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("--name");
expectedCommandLine.add("first test");
expectedCommandLine.add("foo/test/foo_test.dart");
expectedCommandLine.add("--");
expectedCommandLine.add("--enable-debugging");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
@Test
public void failsForFileWithoutTestScript() {
final BazelTestFields fields = new FakeBazelTestFields(
BazelTestFields.forFile("/workspace/foo/test/foo_test.dart", null),
"scripts/daemon.sh",
"scripts/devtools.sh",
"scripts/doctor.sh",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
boolean didThrow = false;
try {
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
}
catch (ExecutionException e) {
didThrow = true;
}
assertTrue("This test method expected to throw an exception, but did not.", didThrow);
}
@Test
public void failsForTestNameWithoutTestScript() {
final BazelTestFields fields = new FakeBazelTestFields(
BazelTestFields.forTestName("first test", "/workspace/foo/test/foo_test.dart", null),
"scripts/daemon.sh",
"scripts/devtools.sh",
"scripts/doctor.sh",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
boolean didThrow = false;
try {
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
}
catch (ExecutionException e) {
didThrow = true;
}
assertTrue("This test method expected to throw an exception, but did not.", didThrow);
}
@Test
public void failsForTestNameAndBazelTargetWithoutTestScript() {
final BazelTestFields fields = new FakeBazelTestFields(
new BazelTestFields(null, "/workspace/foo/test/foo_test.dart", "//foo:test", "--ignored-args"),
"scripts/daemon.sh",
"scripts/devtools.sh",
"scripts/doctor.sh",
null,
null,
null,
null,
null,
null,
null,
null,
null,
null
);
boolean didThrow = false;
try {
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
}
catch (ExecutionException e) {
didThrow = true;
}
assertTrue("This test method expected to throw an exception, but did not.", didThrow);
}
@Test
public void runsInFileModeWhenBothFileAndBazelTargetAreProvided() throws ExecutionException {
final BazelTestFields fields = new FakeBazelTestFields(
new BazelTestFields(null, "/workspace/foo/test/foo_test.dart", "//foo:test", "--arg1 --arg2 3")
);
final GeneralCommandLine launchCommand = fields.getLaunchCommand(projectFixture.getProject(), RunMode.RUN);
final List<String> expectedCommandLine = new ArrayList<>();
expectedCommandLine.add(platformize("/workspace/scripts/flutter-test.sh"));
expectedCommandLine.add("--arg1");
expectedCommandLine.add("--arg2");
expectedCommandLine.add("3");
expectedCommandLine.add("--no-color");
expectedCommandLine.add("--machine");
expectedCommandLine.add("foo/test/foo_test.dart");
assertThat(launchCommand.getCommandLineList(null), equalTo(expectedCommandLine));
}
private FakeBazelTestFields forFile(String file) {
return new FakeBazelTestFields(BazelTestFields.forFile(file, null));
}
private FakeBazelTestFields forTestName(String testName, String file) {
return new FakeBazelTestFields(BazelTestFields.forTestName(testName, file, null));
}
private FakeBazelTestFields forTarget(String target) {
return new FakeBazelTestFields(BazelTestFields.forTarget(target, null));
}
private String platformize(String s) {
return SystemInfo.isWindows ? s.replaceAll("/", "\\\\") : s;
}
/**
* Fake bazel test fields that doesn't depend on the Dart SDK.
*/
private static class FakeBazelTestFields extends BazelTestFields {
final MockVirtualFileSystem fs;
final Workspace fakeWorkspace;
FakeBazelTestFields(@NotNull BazelTestFields template,
@Nullable String daemonScript,
@Nullable String devToolsScript,
@Nullable String doctorScript,
@Nullable String testScript,
@Nullable String runScript,
@Nullable String syncScript,
@Nullable String toolsScript,
@Nullable String sdkHome,
@Nullable String versionFile,
@Nullable String requiredIJPluginID,
@Nullable String requiredIJPluginMessage,
@Nullable String configWarningMessage,
@Nullable String updatedIosRunMessage) {
super(template);
final Pair.NonNull<MockVirtualFileSystem, Workspace> pair = FakeWorkspaceFactory
.createWorkspaceAndFilesystem(daemonScript, devToolsScript, doctorScript, testScript, runScript, syncScript, toolsScript, sdkHome, versionFile,
requiredIJPluginID, requiredIJPluginMessage, configWarningMessage, updatedIosRunMessage);
fs = pair.first;
fakeWorkspace = pair.second;
}
FakeBazelTestFields(@NotNull BazelTestFields template) {
super(template);
final Pair.NonNull<MockVirtualFileSystem, Workspace> pair = FakeWorkspaceFactory.createWorkspaceAndFilesystem();
fs = pair.first;
fakeWorkspace = pair.second;
}
@Override
void checkRunnable(@NotNull Project project) throws RuntimeConfigurationError {
// Skip the Dart VM check in test code.
getScope(project).checkRunnable(this, project);
}
@Nullable
@Override
protected Workspace getWorkspace(@NotNull Project project) {
return fakeWorkspace;
}
@Override
protected void verifyMainFile(Project project) {
// We don't have access to the filesystem in tests, so don't verify anything.
}
}
}
| flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/LaunchCommandsTest.java/0 | {
"file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/bazelTest/LaunchCommandsTest.java",
"repo_id": "flutter-intellij",
"token_count": 4775
} | 519 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.