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_WINDOWS_LIFECYCLE_MANAGER_H_ #define FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWS_LIFECYCLE_MANAGER_H_ #include <Windows.h> #include <cstdint> #include <map> #include <mutex> #include <optional> #include <set> #include "flutter/shell/platform/common/app_lifecycle_state.h" namespace flutter { class FlutterWindowsEngine; /// An event representing a change in window state that may update the // application lifecycle state. enum class WindowStateEvent { kShow, kHide, kFocus, kUnfocus, }; /// A manager for lifecycle events of the top-level windows. /// /// WndProc is called for window messages of the top-level Flutter window. /// ExternalWindowMessage is called for non-flutter top-level window messages. /// OnWindowStateEvent is called when the visibility or focus state of a window /// is changed, including the FlutterView window. class WindowsLifecycleManager { public: WindowsLifecycleManager(FlutterWindowsEngine* engine); virtual ~WindowsLifecycleManager(); // Called when the engine is notified it should quit, e.g. by an application // call to `exitApplication`. When window is std::nullopt, this quits the // application. Otherwise, it holds the HWND of the window that initiated the // request, and exit_code is unused. virtual void Quit(std::optional<HWND> window, std::optional<WPARAM> wparam, std::optional<LPARAM> lparam, UINT exit_code); // Intercept top level window WM_CLOSE message and listen to events that may // update the application lifecycle. bool WindowProc(HWND hwnd, UINT msg, WPARAM w, LPARAM l, LRESULT* result); // Signal to start sending lifecycle state update messages. virtual void BeginProcessingLifecycle(); // Signal to start consuming WM_CLOSE messages. virtual void BeginProcessingExit(); // Update the app lifecycle state in response to a change in window state. // When the app lifecycle state actually changes, this sends a platform // message to the framework notifying it of the state change. virtual void SetLifecycleState(AppLifecycleState state); // Respond to a change in window state. Transitions as follows: // When the only visible window is hidden, transition from resumed or // inactive to hidden. // When the only focused window is unfocused, transition from resumed to // inactive. // When a window is focused, transition from inactive to resumed. // When a window is shown, transition from hidden to inactive. virtual void OnWindowStateEvent(HWND hwnd, WindowStateEvent event); AppLifecycleState GetLifecycleState() { return state_; } // Called by the engine when a non-Flutter window receives an event that may // alter the lifecycle state. The logic for external windows must differ from // that used for FlutterWindow instances, because: // - FlutterWindow does not receive WM_SHOW messages, // - When FlutterWindow receives WM_SIZE messages, wparam stores no meaningful // information, whereas it usually indicates the action which changed the // window size. // When this returns a result, the message has been consumed and should not be // processed further. Currently, it will always return nullopt. std::optional<LRESULT> ExternalWindowMessage(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam); protected: // Check the number of top-level windows associated with this process, and // return true only if there are 1 or fewer. virtual bool IsLastWindowOfProcess(); virtual void DispatchMessage(HWND window, UINT msg, WPARAM wparam, LPARAM lparam); private: // Pass top-level window close notifications to the application lifecycle // logic. If the last window of the process receives WM_CLOSE and a listener // is registered for WidgetsBindingObserver.didRequestAppExit, the message is // sent to the framework to query whether the application should be allowed // to quit. bool HandleCloseMessage(HWND hwnd, WPARAM wparam, LPARAM lparam); FlutterWindowsEngine* engine_; std::map<std::tuple<HWND, WPARAM, LPARAM>, int> sent_close_messages_; bool process_lifecycle_ = false; bool process_exit_ = false; std::set<HWND> visible_windows_; std::set<HWND> focused_windows_; std::mutex state_update_lock_; flutter::AppLifecycleState state_; }; } // namespace flutter #endif // FLUTTER_SHELL_PLATFORM_WINDOWS_WINDOWS_LIFECYCLE_MANAGER_H_
engine/shell/platform/windows/windows_lifecycle_manager.h/0
{ "file_path": "engine/shell/platform/windows/windows_lifecycle_manager.h", "repo_id": "engine", "token_count": 1586 }
371
// 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. // FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/68332 #include "flutter/shell/version/version.h" namespace flutter { const char* GetFlutterEngineVersion() { return FLUTTER_ENGINE_VERSION; } const char* GetSkiaVersion() { return SKIA_VERSION; } const char* GetDartVersion() { return DART_VERSION; } } // namespace flutter
engine/shell/version/version.cc/0
{ "file_path": "engine/shell/version/version.cc", "repo_id": "engine", "token_count": 167 }
372
#!/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 errno import os import shutil import sys def main(): parser = argparse.ArgumentParser( description='Removes existing files and installs the specified headers' + 'at the given location.' ) parser.add_argument( '--headers', nargs='+', help='The headers to install at the location.', required=True ) parser.add_argument('--location', type=str, required=True) args = parser.parse_args() # Remove old headers. try: shutil.rmtree(os.path.normpath(args.location)) except OSError as err: # Ignore only "not found" errors. if err.errno != errno.ENOENT: raise err # Create the directory to copy the files to. if not os.path.isdir(args.location): os.makedirs(args.location) # Copy all files specified in the args. for header_file in args.headers: shutil.copyfile(header_file, os.path.join(args.location, os.path.basename(header_file))) if __name__ == '__main__': sys.exit(main())
engine/sky/tools/install_framework_headers.py/0
{ "file_path": "engine/sky/tools/install_framework_headers.py", "repo_id": "engine", "token_count": 390 }
373
# 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 sys import argparse import os import zipfile import subprocess def run_command_checked(command): try: subprocess.check_output(command, stderr=subprocess.STDOUT, text=True) except subprocess.CalledProcessError as cpe: print(cpe.output) raise cpe def main(): parser = argparse.ArgumentParser() parser.add_argument('--aapt2-bin', type=str, required=True, help='The path to the aapt2 binary.') parser.add_argument( '--zipalign-bin', type=str, required=True, help='The path to the zipalign binary.' ) parser.add_argument( '--apksigner-bin', type=str, required=True, help='The path to the apksigner binary.' ) parser.add_argument( '--android-manifest', type=str, required=True, help='The path to the AndroidManifest.xml.' ) parser.add_argument('--android-jar', type=str, required=True, help='The path to android.jar.') parser.add_argument('--output-path', type=str, required=True, help='The path to the output apk.') parser.add_argument( '--library', type=str, required=True, help='The path to the library to put in the apk.' ) parser.add_argument( '--keystore', type=str, required=True, help='The path to the debug keystore to sign the apk.' ) parser.add_argument( '--gen-dir', type=str, required=True, help='The directory for generated files.' ) parser.add_argument( '--android-abi', type=str, required=True, help='The android ABI of the library.' ) args = parser.parse_args() library_file = os.path.basename(args.library) apk_name = os.path.basename(args.output_path) unaligned_apk_path = os.path.join(args.gen_dir, '%s.unaligned' % apk_name) unsigned_apk_path = os.path.join(args.gen_dir, '%s.unsigned' % apk_name) apk_path = args.output_path # Create the skeleton of the APK using aapt2. aapt2_command = [ args.aapt2_bin, 'link', '-I', args.android_jar, '--manifest', args.android_manifest, '-o', unaligned_apk_path, ] run_command_checked(aapt2_command) # Stuff the library in the APK which is just a regular ZIP file. Libraries are not compressed. with zipfile.ZipFile(unaligned_apk_path, 'a', compression=zipfile.ZIP_STORED) as zipf: zipf.write(args.library, 'lib/%s/%s' % (args.android_abi, library_file)) # Align the dylib to a page boundary. zipalign_command = [ args.zipalign_bin, '-p', # Page align the dylib '-f', # overwrite output if exists '4', # 32-bit alignment unaligned_apk_path, unsigned_apk_path, ] run_command_checked(zipalign_command) # Sign the APK. apksigner_command = [ args.apksigner_bin, 'sign', '--ks', args.keystore, '--ks-pass', 'pass:android', '--out', apk_path, unsigned_apk_path ] run_command_checked(apksigner_command) return 0 if __name__ == '__main__': sys.exit(main())
engine/testing/android/native_activity/native_activity_apk.py/0
{ "file_path": "engine/testing/android/native_activity/native_activity_apk.py", "repo_id": "engine", "token_count": 1152 }
374
#!/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 os import subprocess import sys BUILDROOT_DIR = os.path.abspath(os.path.join(os.path.realpath(__file__), '..', '..', '..')) PERFETTO_SESSION_KEY = 'session1' PERFETTO_TRACE_FILE = '/data/misc/perfetto-traces/trace' PERFETTO_CONFIG = """ write_into_file: true file_write_period_ms: 1000000000 flush_period_ms: 1000 buffers: { size_kb: 129024 } data_sources: { config { name: "linux.ftrace" ftrace_config { ftrace_events: "ftrace/print" atrace_apps: "%s" } } } """ def install_apk(apk_path, package_name, adb_path='adb'): print('Installing APK') subprocess.check_output([adb_path, 'shell', 'am', 'force-stop', package_name]) # Allowed to fail if APK was never installed. subprocess.call([adb_path, 'uninstall', package_name], stdout=subprocess.DEVNULL) subprocess.check_output([adb_path, 'install', apk_path]) def start_perfetto(package_name, adb_path='adb'): print('Starting trace') cmd = [ adb_path, 'shell', 'echo', "'" + PERFETTO_CONFIG % package_name + "'", '|', 'perfetto', '-c', '-', '--txt', '-o', PERFETTO_TRACE_FILE, '--detach', PERFETTO_SESSION_KEY ] subprocess.check_output(cmd, stderr=subprocess.STDOUT) def launch_package(package_name, activity_name, adb_path='adb'): print('Scanning logcat') subprocess.check_output([adb_path, 'logcat', '-c'], stderr=subprocess.STDOUT) logcat = subprocess.Popen([adb_path, 'logcat'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) print('Launching %s (%s)' % (package_name, activity_name)) subprocess.check_output([ adb_path, 'shell', 'am ', 'start', '-n', '%s/%s' % (package_name, activity_name) ], stderr=subprocess.STDOUT) for line in logcat.stdout: print('>>>>>>>> ' + line.strip()) if ('Observatory listening' in line) or ('Dart VM service is listening' in line): logcat.kill() break def collect_and_validate_trace(adb_path='adb'): print('Fetching trace') subprocess.check_output([ adb_path, 'shell', 'perfetto', '--attach', PERFETTO_SESSION_KEY, '--stop' ], stderr=subprocess.STDOUT) subprocess.check_output([adb_path, 'pull', PERFETTO_TRACE_FILE, 'trace.pb'], stderr=subprocess.STDOUT) print('Validating trace') traceconv = os.path.join( BUILDROOT_DIR, 'third_party', 'android_tools', 'trace_to_text', 'trace_to_text' ) traceconv_output = subprocess.check_output([traceconv, 'systrace', 'trace.pb'], stderr=subprocess.STDOUT, universal_newlines=True) print('Trace output:') print(traceconv_output) if 'ShellSetupUISubsystem' in traceconv_output: return 0 print('Trace did not contain ShellSetupUISubsystem, failing.') return 1 def main(): parser = argparse.ArgumentParser() parser.add_argument( '--apk-path', dest='apk_path', action='store', help='Provide the path to the APK to install' ) parser.add_argument( '--package-name', dest='package_name', action='store', help='The package name of the APK, e.g. dev.flutter.scenarios' ) parser.add_argument( '--activity-name', dest='activity_name', action='store', help='The activity to launch as it appears in AndroidManifest.xml, ' 'e.g. .PlatformViewsActivity' ) parser.add_argument( '--adb-path', dest='adb_path', action='store', default='adb', help='Provide the path of adb used for android tests. ' 'By default it looks on $PATH.' ) args = parser.parse_args() android_api_level = subprocess.check_output([ args.adb_path, 'shell', 'getprop', 'ro.build.version.sdk' ], text=True).strip() if int(android_api_level) < 29: print('Android API %s detected. This script requires API 29 or above.' % android_api_level) return 0 install_apk(args.apk_path, args.package_name, args.adb_path) start_perfetto(args.package_name, args.adb_path) launch_package(args.package_name, args.activity_name, args.adb_path) return collect_and_validate_trace(args.adb_path) if __name__ == '__main__': sys.exit(main())
engine/testing/android_systrace_test.py/0
{ "file_path": "engine/testing/android_systrace_test.py", "repo_id": "engine", "token_count": 1991 }
375
# 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") tests = [ "skp_test.dart", "tracing_test.dart", "shader_reload_test.dart", "vmservice_methods_test.dart", ] foreach(test, tests) { flutter_frontend_server("compile_$test") { main_dart = test kernel_output = "$root_gen_dir/$test.dill" package_config = "../.dart_tool/package_config.json" } } group("observatory") { testonly = true deps = [] foreach(test, tests) { deps += [ ":compile_$test" ] } }
engine/testing/dart/observatory/BUILD.gn/0
{ "file_path": "engine/testing/dart/observatory/BUILD.gn", "repo_id": "engine", "token_count": 255 }
376
// 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/display_list_testing.h" #include <iomanip> #include "flutter/display_list/display_list.h" namespace flutter { namespace testing { // clang-format off bool DisplayListsEQ_Verbose(const DisplayList* a, const DisplayList* b) { if (a->Equals(b)) { return true; } FML_LOG(ERROR) << std::endl << std::endl << *a << std::endl << "not identical to ..." << std::endl << std::endl << *b; return false; } bool DisplayListsNE_Verbose(const DisplayList* a, const DisplayList* b) { if (a->Equals(b)) { FML_LOG(ERROR) << std::endl << "DisplayLists are both the same:" << std::endl << *a; return false; } return true; } std::ostream& operator<<(std::ostream& os, const DisplayList& display_list) { DisplayListStreamDispatcher dispatcher(os); os << std::boolalpha; os << std::setprecision(std::numeric_limits<long double>::digits10 + 1); os << "DisplayList {" << std::endl; display_list.Dispatch(dispatcher); os << "}" << std::endl; return os; } std::ostream& operator<<(std::ostream& os, const DlPaint& paint) { os << "DlPaint(" << "isaa: " << paint.isAntiAlias() << ", " << paint.getColor() << ", " << paint.getBlendMode() << ", " << paint.getDrawStyle(); if (paint.getDrawStyle() != DlDrawStyle::kFill) { os << ", width: " << paint.getStrokeWidth() << ", miter: " << paint.getStrokeMiter() << ", " << paint.getStrokeCap() << ", " << paint.getStrokeJoin(); } if (paint.getColorSource()) { os << ", " << paint.getColorSource(); } if (paint.getColorFilter()) { os << ", " << paint.getColorFilter(); } if (paint.getImageFilter()) { os << ", " << paint.getImageFilter(); } if (paint.getMaskFilter()) { os << ", " << paint.getMaskFilter(); } if (paint.isInvertColors()) { os << ", invertColors: " << paint.isInvertColors(); } return os << ")"; } std::ostream& operator<<(std::ostream& os, const DlBlendMode& mode) { switch (mode) { case DlBlendMode::kClear: return os << "BlendMode::kClear"; case DlBlendMode::kSrc: return os << "BlendMode::kSrc"; case DlBlendMode::kDst: return os << "BlendMode::kDst"; case DlBlendMode::kSrcOver: return os << "BlendMode::kSrcOver"; case DlBlendMode::kDstOver: return os << "BlendMode::kDstOver"; case DlBlendMode::kSrcIn: return os << "BlendMode::kSrcIn"; case DlBlendMode::kDstIn: return os << "BlendMode::kDstIn"; case DlBlendMode::kSrcOut: return os << "BlendMode::kSrcOut"; case DlBlendMode::kDstOut: return os << "BlendMode::kDstOut"; case DlBlendMode::kSrcATop: return os << "BlendMode::kSrcATop"; case DlBlendMode::kDstATop: return os << "BlendMode::kDstATop"; case DlBlendMode::kXor: return os << "BlendMode::kXor"; case DlBlendMode::kPlus: return os << "BlendMode::kPlus"; case DlBlendMode::kModulate: return os << "BlendMode::kModulate"; case DlBlendMode::kScreen: return os << "BlendMode::kScreen"; case DlBlendMode::kOverlay: return os << "BlendMode::kOverlay"; case DlBlendMode::kDarken: return os << "BlendMode::kDarken"; case DlBlendMode::kLighten: return os << "BlendMode::kLighten"; case DlBlendMode::kColorDodge: return os << "BlendMode::kColorDodge"; case DlBlendMode::kColorBurn: return os << "BlendMode::kColorBurn"; case DlBlendMode::kHardLight: return os << "BlendMode::kHardLight"; case DlBlendMode::kSoftLight: return os << "BlendMode::kSoftLight"; case DlBlendMode::kDifference: return os << "BlendMode::kDifference"; case DlBlendMode::kExclusion: return os << "BlendMode::kExclusion"; case DlBlendMode::kMultiply: return os << "BlendMode::kMultiply"; case DlBlendMode::kHue: return os << "BlendMode::kHue"; case DlBlendMode::kSaturation: return os << "BlendMode::kSaturation"; case DlBlendMode::kColor: return os << "BlendMode::kColor"; case DlBlendMode::kLuminosity: return os << "BlendMode::kLuminosity"; default: return os << "BlendMode::????"; } } std::ostream& operator<<(std::ostream& os, const SaveLayerOptions& options) { return os << "SaveLayerOptions(" << "can_distribute_opacity: " << options.can_distribute_opacity() << ", " << "renders_with_attributes: " << options.renders_with_attributes() << ")"; } static std::ostream& operator<<(std::ostream& os, const SkPoint& point) { return os << "SkPoint(" << point.fX << ", " << point.fY << ")"; } static std::ostream& operator<<(std::ostream& os, const SkIRect& rect) { return os << "SkIRect(" << "left: " << rect.fLeft << ", " << "top: " << rect.fTop << ", " << "right: " << rect.fRight << ", " << "bottom: " << rect.fBottom << ")"; } static std::ostream& operator<<(std::ostream& os, const SkRect& rect) { return os << "SkRect(" << "left: " << rect.fLeft << ", " << "top: " << rect.fTop << ", " << "right: " << rect.fRight << ", " << "bottom: " << rect.fBottom << ")"; } static std::ostream& operator<<(std::ostream& os, const SkRect* rect) { return rect ? (os << "&" << *rect) : os << "no rect"; } static std::ostream& operator<<(std::ostream& os, const SkRRect& rrect) { return os << "SkRRect(" << rrect.rect() << ", " << "ul: (" << rrect.radii(SkRRect::kUpperLeft_Corner).fX << ", " << rrect.radii(SkRRect::kUpperLeft_Corner).fY << "), " << "ur: (" << rrect.radii(SkRRect::kUpperRight_Corner).fX << ", " << rrect.radii(SkRRect::kUpperRight_Corner).fY << "), " << "lr: (" << rrect.radii(SkRRect::kLowerRight_Corner).fX << ", " << rrect.radii(SkRRect::kLowerRight_Corner).fY << "), " << "ll: (" << rrect.radii(SkRRect::kLowerLeft_Corner).fX << ", " << rrect.radii(SkRRect::kLowerLeft_Corner).fY << ")" << ")"; } static std::ostream& operator<<(std::ostream& os, const SkPath& path) { return os << "SkPath(" << "bounds: " << path.getBounds() // should iterate over verbs and coordinates... << ")"; } static std::ostream& operator<<(std::ostream& os, const SkMatrix& matrix) { return os << "SkMatrix(" << "[" << matrix[0] << ", " << matrix[1] << ", " << matrix[2] << "], " << "[" << matrix[3] << ", " << matrix[4] << ", " << matrix[5] << "], " << "[" << matrix[6] << ", " << matrix[7] << ", " << matrix[8] << "]" << ")"; } static std::ostream& operator<<(std::ostream& os, const SkMatrix* matrix) { if (matrix) return os << "&" << *matrix; return os << "no matrix"; } static std::ostream& operator<<(std::ostream& os, const SkRSXform& xform) { return os << "SkRSXform(" << "scos: " << xform.fSCos << ", " << "ssin: " << xform.fSSin << ", " << "tx: " << xform.fTx << ", " << "ty: " << xform.fTy << ")"; } std::ostream& operator<<(std::ostream& os, const DlCanvas::ClipOp& op) { switch (op) { case DlCanvas::ClipOp::kDifference: return os << "ClipOp::kDifference"; case DlCanvas::ClipOp::kIntersect: return os << "ClipOp::kIntersect"; } } std::ostream& operator<<(std::ostream& os, const DlCanvas::SrcRectConstraint& constraint) { switch (constraint) { case DlCanvas::SrcRectConstraint::kFast: return os << "SrcRectConstraint::kFast"; case DlCanvas::SrcRectConstraint::kStrict: return os << "SrcRectConstraint::kStrict"; } } std::ostream& operator<<(std::ostream& os, const DlStrokeCap& cap) { switch (cap) { case DlStrokeCap::kButt: return os << "Cap::kButt"; case DlStrokeCap::kRound: return os << "Cap::kRound"; case DlStrokeCap::kSquare: return os << "Cap::kSquare"; } } std::ostream& operator<<(std::ostream& os, const DlStrokeJoin& join) { switch (join) { case DlStrokeJoin::kMiter: return os << "Join::kMiter"; case DlStrokeJoin::kRound: return os << "Join::kRound"; case DlStrokeJoin::kBevel: return os << "Join::kBevel"; } } std::ostream& operator<<(std::ostream& os, const DlDrawStyle& style) { switch (style) { case DlDrawStyle::kFill: return os << "Style::kFill"; case DlDrawStyle::kStroke: return os << "Style::kStroke"; case DlDrawStyle::kStrokeAndFill: return os << "Style::kStrokeAnFill"; } } std::ostream& operator<<(std::ostream& os, const DlBlurStyle& style) { switch (style) { case DlBlurStyle::kNormal: return os << "BlurStyle::kNormal"; case DlBlurStyle::kSolid: return os << "BlurStyle::kSolid"; case DlBlurStyle::kOuter: return os << "BlurStyle::kOuter"; case DlBlurStyle::kInner: return os << "BlurStyle::kInner"; } } std::ostream& operator<<(std::ostream& os, const DlCanvas::PointMode& mode) { switch (mode) { case DlCanvas::PointMode::kPoints: return os << "PointMode::kPoints"; case DlCanvas::PointMode::kLines: return os << "PointMode::kLines"; case DlCanvas::PointMode::kPolygon: return os << "PointMode::kPolygon"; } } std::ostream& operator<<(std::ostream& os, const DlFilterMode& mode) { switch (mode) { case DlFilterMode::kNearest: return os << "FilterMode::kNearest"; case DlFilterMode::kLinear: return os << "FilterMode::kLinear"; default: return os << "FilterMode::????"; } } std::ostream& operator<<(std::ostream& os, const DlColor& color) { return os << "DlColor(" << std::hex << color.argb() << std::dec << ")"; } std::ostream& operator<<(std::ostream& os, DlImageSampling sampling) { switch (sampling) { case DlImageSampling::kNearestNeighbor: { return os << "NearestSampling"; } case DlImageSampling::kLinear: { return os << "LinearSampling"; } case DlImageSampling::kMipmapLinear: { return os << "MipmapSampling"; } case DlImageSampling::kCubic: { return os << "CubicSampling"; } } } static std::ostream& operator<<(std::ostream& os, const SkTextBlob* blob) { if (blob == nullptr) { return os << "no text"; } return os << "&SkTextBlob(ID: " << blob->uniqueID() << ", " << blob->bounds() << ")"; } static std::ostream& operator<<(std::ostream& os, const impeller::TextFrame* frame) { if (frame == nullptr) { return os << "no text"; } auto bounds = frame->GetBounds(); return os << "&TextFrame(" << bounds.GetLeft() << ", " << bounds.GetTop() << " => " << bounds.GetRight() << ", " << bounds.GetBottom() << ")"; } std::ostream& operator<<(std::ostream& os, const DlVertexMode& mode) { switch (mode) { case DlVertexMode::kTriangles: return os << "VertexMode::kTriangles"; case DlVertexMode::kTriangleStrip: return os << "VertexMode::kTriangleStrip"; case DlVertexMode::kTriangleFan: return os << "VertexMode::kTriangleFan"; default: return os << "VertexMode::????"; } } std::ostream& operator<<(std::ostream& os, const DlTileMode& mode) { switch (mode) { case DlTileMode::kClamp: return os << "TileMode::kClamp"; case DlTileMode::kRepeat: return os << "TileMode::kRepeat"; case DlTileMode::kMirror: return os << "TileMode::kMirror"; case DlTileMode::kDecal: return os << "TileMode::kDecal"; default: return os << "TileMode::????"; } } std::ostream& operator<<(std::ostream& os, const DlImage* image) { if (image == nullptr) { return os << "null image"; } os << "&DlImage(" << image->width() << " x " << image->height() << ", "; if (image->skia_image()) { os << "skia(" << image->skia_image().get() << "), "; } if (image->impeller_texture()) { os << "impeller(" << image->impeller_texture().get() << "), "; } return os << "isTextureBacked: " << image->isTextureBacked() << ")"; } std::ostream& DisplayListStreamDispatcher::startl() { for (int i = 0; i < cur_indent_; i++) { os_ << " "; } return os_; } template <class T> std::ostream& DisplayListStreamDispatcher::out_array(std::string name, // NOLINT(performance-unnecessary-value-param) int count, const T array[]) { if (array == nullptr || count < 0) { return os_ << "no " << name; } os_ << name << "[" << count << "] = [" << std::endl; indent(); indent(); for (int i = 0; i < count; i++) { startl() << array[i] << "," << std::endl; } outdent(); startl() << "]"; outdent(); return os_; } void DisplayListStreamDispatcher::setAntiAlias(bool aa) { startl() << "setAntiAlias(" << aa << ");" << std::endl; } void DisplayListStreamDispatcher::setDrawStyle(DlDrawStyle style) { startl() << "setStyle(" << style << ");" << std::endl; } void DisplayListStreamDispatcher::setColor(DlColor color) { startl() << "setColor(" << color << ");" << std::endl; } void DisplayListStreamDispatcher::setStrokeWidth(SkScalar width) { startl() << "setStrokeWidth(" << width << ");" << std::endl; } void DisplayListStreamDispatcher::setStrokeMiter(SkScalar limit) { startl() << "setStrokeMiter(" << limit << ");" << std::endl; } void DisplayListStreamDispatcher::setStrokeCap(DlStrokeCap cap) { startl() << "setStrokeCap(" << cap << ");" << std::endl; } void DisplayListStreamDispatcher::setStrokeJoin(DlStrokeJoin join) { startl() << "setStrokeJoin(" << join << ");" << std::endl; } void DisplayListStreamDispatcher::setColorSource(const DlColorSource* source) { if (source == nullptr) { startl() << "setColorSource(no ColorSource);" << std::endl; return; } startl() << "setColorSource("; switch (source->type()) { case DlColorSourceType::kColor: { const DlColorColorSource* color_src = source->asColor(); FML_DCHECK(color_src); os_ << "DlColorColorSource(" << color_src->color() << ")"; break; } case DlColorSourceType::kImage: { const DlImageColorSource* image_src = source->asImage(); FML_DCHECK(image_src); os_ << "DlImageColorSource(image: " << image_src->image() << ", hMode: " << image_src->horizontal_tile_mode() << ", vMode: " << image_src->vertical_tile_mode() << ", " << image_src->sampling() << ", " << image_src->matrix_ptr() << ")"; break; } case DlColorSourceType::kLinearGradient: { const DlLinearGradientColorSource* linear_src = source->asLinearGradient(); FML_DCHECK(linear_src); os_ << "DlLinearGradientSource(" << "start: " << linear_src->start_point() << ", end: " << linear_src->end_point() << ", "; out_array("colors", linear_src->stop_count(), linear_src->colors()) << ", "; out_array("stops", linear_src->stop_count(), linear_src->stops()) << ", " << linear_src->tile_mode() << ", " << linear_src->matrix_ptr() << ")"; break; } case DlColorSourceType::kRadialGradient: { const DlRadialGradientColorSource* radial_src = source->asRadialGradient(); FML_DCHECK(radial_src); os_ << "DlRadialGradientSource(" << "center: " << radial_src->center() << ", radius: " << radial_src->radius() << ", "; out_array("colors", radial_src->stop_count(), radial_src->colors()) << ", "; out_array("stops", radial_src->stop_count(), radial_src->stops()) << ", " << radial_src->tile_mode() << ", " << radial_src->matrix_ptr() << ")"; break; } case DlColorSourceType::kConicalGradient: { const DlConicalGradientColorSource* conical_src = source->asConicalGradient(); FML_DCHECK(conical_src); os_ << "DlConicalGradientColorSource(" << "start center: " << conical_src->start_center() << ", start radius: " << conical_src->start_radius() << ", end center: " << conical_src->end_center() << ", end radius: " << conical_src->end_radius() << ", "; out_array("colors", conical_src->stop_count(), conical_src->colors()) << ", "; out_array("stops", conical_src->stop_count(), conical_src->stops()) << ", " << conical_src->tile_mode() << ", " << conical_src->matrix_ptr() << ")"; break; } case DlColorSourceType::kSweepGradient: { const DlSweepGradientColorSource* sweep_src = source->asSweepGradient(); FML_DCHECK(sweep_src); os_ << "DlSweepGradientColorSource(" << "center: " << sweep_src->center() << ", start: " << sweep_src->start() << ", " << ", end: " << sweep_src->end() << ", "; out_array("colors", sweep_src->stop_count(), sweep_src->colors()) << ", "; out_array("stops", sweep_src->stop_count(), sweep_src->stops()) << ", " << sweep_src->tile_mode() << ", " << sweep_src->matrix_ptr() << ")"; break; } default: os_ << "?DlUnknownColorSource?()"; break; } os_ << ");" << std::endl; } void DisplayListStreamDispatcher::out(const DlColorFilter& filter) { switch (filter.type()) { case DlColorFilterType::kBlend: { const DlBlendColorFilter* blend = filter.asBlend(); FML_DCHECK(blend); os_ << "DlBlendColorFilter(" << blend->color() << ", " << static_cast<int>(blend->mode()) << ")"; break; } case DlColorFilterType::kMatrix: { const DlMatrixColorFilter* matrix = filter.asMatrix(); FML_DCHECK(matrix); float values[20]; matrix->get_matrix(values); os_ << "DlMatrixColorFilter(matrix[20] = [" << std::endl; indent(); for (int i = 0; i < 20; i += 5) { startl() << values[i] << ", " << values[i+1] << ", " << values[i+2] << ", " << values[i+3] << ", " << values[i+4] << "," << std::endl; } outdent(); startl() << "]"; break; } case DlColorFilterType::kSrgbToLinearGamma: { os_ << "DlSrgbToLinearGammaColorFilter()"; break; } case DlColorFilterType::kLinearToSrgbGamma: { os_ << "DlLinearToSrgbGammaColorFilter()"; break; } default: os_ << "?DlUnknownColorFilter?()"; break; } } void DisplayListStreamDispatcher::out(const DlColorFilter* filter) { if (filter == nullptr) { os_ << "no ColorFilter"; } else { os_ << "&"; out(*filter); } } void DisplayListStreamDispatcher::setColorFilter(const DlColorFilter* filter) { startl() << "setColorFilter("; out(filter); os_ << ");" << std::endl; } void DisplayListStreamDispatcher::setInvertColors(bool invert) { startl() << "setInvertColors(" << invert << ");" << std::endl; } void DisplayListStreamDispatcher::setBlendMode(DlBlendMode mode) { startl() << "setBlendMode(" << mode << ");" << std::endl; } void DisplayListStreamDispatcher::setPathEffect(const DlPathEffect* effect) { startl() << "setPathEffect(" << effect << ");" << std::endl; } void DisplayListStreamDispatcher::setMaskFilter(const DlMaskFilter* filter) { if (filter == nullptr) { startl() << "setMaskFilter(no MaskFilter);" << std::endl; return; } startl() << "setMaskFilter("; switch (filter->type()) { case DlMaskFilterType::kBlur: { const DlBlurMaskFilter* blur = filter->asBlur(); FML_DCHECK(blur); os_ << "DlMaskFilter(" << blur->style() << ", " << blur->sigma() << ")"; break; } default: os_ << "?DlUnknownMaskFilter?()"; break; } os_ << ");" << std::endl; } void DisplayListStreamDispatcher::out(const DlImageFilter& filter) { switch (filter.type()) { case DlImageFilterType::kBlur: { const DlBlurImageFilter* blur = filter.asBlur(); FML_DCHECK(blur); os_ << "DlBlurImageFilter(" << blur->sigma_x() << ", " << blur->sigma_y() << ", " << blur->tile_mode() << ")"; break; } case DlImageFilterType::kDilate: { const DlDilateImageFilter* dilate = filter.asDilate(); FML_DCHECK(dilate); os_ << "DlDilateImageFilter(" << dilate->radius_x() << ", " << dilate->radius_y() << ")"; break; } case DlImageFilterType::kErode: { const DlErodeImageFilter* erode = filter.asErode(); FML_DCHECK(erode); os_ << "DlDilateImageFilter(" << erode->radius_x() << ", " << erode->radius_y() << ")"; break; } case DlImageFilterType::kMatrix: { const DlMatrixImageFilter* matrix = filter.asMatrix(); FML_DCHECK(matrix); os_ << "DlMatrixImageFilter(" << matrix->matrix() << ", " << matrix->sampling() << ")"; break; } case DlImageFilterType::kCompose: { const DlComposeImageFilter* compose = filter.asCompose(); FML_DCHECK(compose); os_ << "DlComposeImageFilter(" << std::endl; indent(); startl() << "outer: "; indent(7); out(compose->outer().get()); os_ << "," << std::endl; outdent(7); startl() << "inner: "; indent(7); out(compose->inner().get()); os_ << std::endl; outdent(7); outdent(); startl() << ")"; break; } case DlImageFilterType::kColorFilter: { const DlColorFilterImageFilter* color_filter = filter.asColorFilter(); FML_DCHECK(color_filter); os_ << "DlColorFilterImageFilter("; out(*color_filter->color_filter()); os_ << ")"; break; } case DlImageFilterType::kLocalMatrix: { const DlLocalMatrixImageFilter* local_matrix = filter.asLocalMatrix(); FML_DCHECK(local_matrix); os_ << "DlLocalMatrixImageFilter(" << local_matrix->matrix(); os_ << "," << std::endl; indent(25); startl() << "filter: "; out(local_matrix->image_filter().get()); os_ << std::endl; outdent(25); startl() << ")"; break; } } } void DisplayListStreamDispatcher::out(const DlImageFilter* filter) { if (filter == nullptr) { os_ << "no ImageFilter"; } else { os_ << "&"; indent(1); out(*filter); outdent(1); } } void DisplayListStreamDispatcher::setImageFilter(const DlImageFilter* filter) { startl() << "setImageFilter("; indent(15); out(filter); outdent(15); os_ << ");" << std::endl; } void DisplayListStreamDispatcher::save() { startl() << "save();" << std::endl; startl() << "{" << std::endl; indent(); } void DisplayListStreamDispatcher::saveLayer(const SkRect& bounds, const SaveLayerOptions options, const DlImageFilter* backdrop) { startl() << "saveLayer(" << bounds << ", " << options; if (backdrop) { os_ << "," << std::endl; indent(10); startl() << "backdrop: "; out(backdrop); outdent(10); } else { os_ << ", no backdrop"; } os_ << ");" << std::endl; startl() << "{" << std::endl; indent(); } void DisplayListStreamDispatcher::restore() { outdent(); startl() << "}" << std::endl; startl() << "restore();" << std::endl; } void DisplayListStreamDispatcher::translate(SkScalar tx, SkScalar ty) { startl() << "translate(" << tx << ", " << ty << ");" << std::endl; } void DisplayListStreamDispatcher::scale(SkScalar sx, SkScalar sy) { startl() << "scale(" << sx << ", " << sy << ");" << std::endl; } void DisplayListStreamDispatcher::rotate(SkScalar degrees) { startl() << "rotate(" << degrees << ");" << std::endl; } void DisplayListStreamDispatcher::skew(SkScalar sx, SkScalar sy) { startl() << "skew(" << sx << ", " << sy << ");" << std::endl; } void DisplayListStreamDispatcher::transform2DAffine( SkScalar mxx, SkScalar mxy, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myt) { startl() << "transform2DAffine(" << std::endl; indent(); { startl() << "[" << mxx << ", " << mxy << ", " << mxt << "], " << std::endl; startl() << "[" << myx << ", " << myy << ", " << myt << "], " << std::endl; } outdent(); startl() << ");" << std::endl; } void DisplayListStreamDispatcher::transformFullPerspective( SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) { startl() << "transformFullPerspective(" << std::endl; indent(); { startl() << "[" << mxx << ", " << mxy << ", " << mxz << ", " << mxt << "], " << std::endl; startl() << "[" << myx << ", " << myy << ", " << myz << ", " << myt << "], " << std::endl; startl() << "[" << mzx << ", " << mzy << ", " << mzz << ", " << mzt << "], " << std::endl; startl() << "[" << mwx << ", " << mwy << ", " << mwz << ", " << mwt << "]" << std::endl; } outdent(); startl() << ");" << std::endl; } void DisplayListStreamDispatcher::transformReset() { startl() << "transformReset();" << std::endl; } void DisplayListStreamDispatcher::clipRect(const SkRect& rect, ClipOp clip_op, bool is_aa) { startl() << "clipRect(" << rect << ", " << clip_op << ", " << "isaa: " << is_aa << ");" << std::endl; } void DisplayListStreamDispatcher::clipRRect(const SkRRect& rrect, ClipOp clip_op, bool is_aa) { startl() << "clipRRect(" << rrect << ", " << clip_op << ", " << "isaa: " << is_aa << ");" << std::endl; } void DisplayListStreamDispatcher::clipPath(const SkPath& path, ClipOp clip_op, bool is_aa) { startl() << "clipPath(" << path << ", " << clip_op << ", " << "isaa: " << is_aa << ");" << std::endl; } void DisplayListStreamDispatcher::drawColor(DlColor color, DlBlendMode mode) { startl() << "drawColor(" << color << ", " << mode << ");" << std::endl; } void DisplayListStreamDispatcher::drawPaint() { startl() << "drawPaint();" << std::endl; } void DisplayListStreamDispatcher::drawLine(const SkPoint& p0, const SkPoint& p1) { startl() << "drawLine(" << p0 << ", " << p1 << ");" << std::endl; } void DisplayListStreamDispatcher::drawRect(const SkRect& rect) { startl() << "drawRect(" << rect << ");" << std::endl; } void DisplayListStreamDispatcher::drawOval(const SkRect& bounds) { startl() << "drawOval(" << bounds << ");" << std::endl; } void DisplayListStreamDispatcher::drawCircle(const SkPoint& center, SkScalar radius) { startl() << "drawCircle(" << center << ", " << radius << ");" << std::endl; } void DisplayListStreamDispatcher::drawRRect(const SkRRect& rrect) { startl() << "drawRRect(" << rrect << ");" << std::endl; } void DisplayListStreamDispatcher::drawDRRect(const SkRRect& outer, const SkRRect& inner) { startl() << "drawDRRect(outer: " << outer << ", " << std::endl; startl() << " inner: " << inner << ");" << std::endl; } void DisplayListStreamDispatcher::drawPath(const SkPath& path) { startl() << "drawPath(" << path << ");" << std::endl; } void DisplayListStreamDispatcher::drawArc(const SkRect& oval_bounds, SkScalar start_degrees, SkScalar sweep_degrees, bool use_center) { startl() << "drawArc(" << oval_bounds << ", " << start_degrees << ", " << sweep_degrees << ", " << "use_center: " << use_center << ");" << std::endl; } void DisplayListStreamDispatcher::drawPoints(PointMode mode, uint32_t count, const SkPoint points[]) { startl() << "drawPoints(" << mode << ", "; out_array("points", count, points) << ");" << std::endl; } void DisplayListStreamDispatcher::drawVertices(const DlVertices* vertices, DlBlendMode mode) { startl() << "drawVertices(" << "DlVertices(" << vertices->mode() << ", "; out_array("vertices", vertices->vertex_count(), vertices->vertices()) << ", "; out_array("texture_coords", vertices->vertex_count(), vertices->texture_coordinates()) << ", "; out_array("colors", vertices->vertex_count(), vertices->colors()) << ", "; out_array("indices", vertices->index_count(), vertices->indices()) << "), " << mode << ");" << std::endl; } void DisplayListStreamDispatcher::drawImage(const sk_sp<DlImage> image, const SkPoint point, DlImageSampling sampling, bool render_with_attributes) { startl() << "drawImage(" << image.get() << "," << std::endl; startl() << " " << point << ", " << sampling << ", " << "with attributes: " << render_with_attributes << ");" << std::endl; } void DisplayListStreamDispatcher::drawImageRect(const sk_sp<DlImage> image, const SkRect& src, const SkRect& dst, DlImageSampling sampling, bool render_with_attributes, SrcRectConstraint constraint) { startl() << "drawImageRect(" << image.get() << "," << std::endl; startl() << " src: " << src << "," << std::endl; startl() << " dst: " << dst << "," << std::endl; startl() << " " << sampling << ", " << "with attributes: " << render_with_attributes << ", " << constraint << ");" << std::endl; } void DisplayListStreamDispatcher::drawImageNine(const sk_sp<DlImage> image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, bool render_with_attributes) { startl() << "drawImageNine(" << image.get() << "," << std::endl; startl() << " center: " << center << "," << std::endl; startl() << " dst: " << dst << "," << std::endl; startl() << " " << filter << ", " << "with attributes: " << render_with_attributes << ");" << std::endl; } void DisplayListStreamDispatcher::drawAtlas(const sk_sp<DlImage> atlas, const SkRSXform xform[], const SkRect tex[], const DlColor colors[], int count, DlBlendMode mode, DlImageSampling sampling, const SkRect* cull_rect, bool render_with_attributes) { startl() << "drawAtlas(" << atlas.get() << ", "; out_array("xforms", count, xform) << ", "; out_array("tex_coords", count, tex) << ", "; out_array("colors", count, colors) << ", " << mode << ", " << sampling << ", cull: " << cull_rect << ", " << "with attributes: " << render_with_attributes << ");" << std::endl; } void DisplayListStreamDispatcher::drawDisplayList( const sk_sp<DisplayList> display_list, SkScalar opacity) { startl() << "drawDisplayList(" << "ID: " << display_list->unique_id() << ", " << "bounds: " << display_list->bounds() << ", " << "opacity: " << opacity << ");" << std::endl; } void DisplayListStreamDispatcher::drawTextBlob(const sk_sp<SkTextBlob> blob, SkScalar x, SkScalar y) { startl() << "drawTextBlob(" << blob.get() << ", " << x << ", " << y << ");" << std::endl; } void DisplayListStreamDispatcher::drawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y) { startl() << "drawTextFrame(" << text_frame.get() << ", " << x << ", " << y << ");" << std::endl; } void DisplayListStreamDispatcher::drawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) { startl() << "drawShadow(" << path << ", " << color << ", " << elevation << ", " << transparent_occluder << ", " << dpr << ");" << std::endl; } // clang-format on } // namespace testing } // namespace flutter
engine/testing/display_list_testing.cc/0
{ "file_path": "engine/testing/display_list_testing.cc", "repo_id": "engine", "token_count": 16456 }
377
// 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/mock_canvas.h" #include "flutter/fml/logging.h" #include "flutter/testing/display_list_testing.h" #include "third_party/skia/include/core/SkImageInfo.h" #include "third_party/skia/include/core/SkSerialProcs.h" #include "third_party/skia/include/core/SkSize.h" #include "third_party/skia/include/core/SkTextBlob.h" namespace flutter { namespace testing { constexpr SkISize kSize = SkISize::Make(64, 64); MockCanvas::MockCanvas() : tracker_(SkRect::Make(kSize), SkMatrix::I()), current_layer_(0) {} MockCanvas::MockCanvas(int width, int height) : tracker_(SkRect::MakeIWH(width, height), SkMatrix::I()), current_layer_(0) {} MockCanvas::~MockCanvas() { EXPECT_EQ(current_layer_, 0); } SkISize MockCanvas::GetBaseLayerSize() const { return tracker_.base_device_cull_rect().roundOut().size(); } SkImageInfo MockCanvas::GetImageInfo() const { SkISize size = GetBaseLayerSize(); return SkImageInfo::MakeUnknown(size.width(), size.height()); } void MockCanvas::Save() { draw_calls_.emplace_back( DrawCall{current_layer_, SaveData{current_layer_ + 1}}); tracker_.save(); current_layer_++; // Must go here; func params order of eval is undefined } void MockCanvas::SaveLayer(const SkRect* bounds, const DlPaint* paint, const DlImageFilter* backdrop) { // saveLayer calls this prior to running, so we use it to track saveLayer // calls draw_calls_.emplace_back(DrawCall{ current_layer_, SaveLayerData{bounds ? *bounds : SkRect(), paint ? *paint : DlPaint(), backdrop ? backdrop->shared() : nullptr, current_layer_ + 1}}); tracker_.save(); current_layer_++; // Must go here; func params order of eval is undefined } void MockCanvas::Restore() { FML_DCHECK(current_layer_ > 0); draw_calls_.emplace_back( DrawCall{current_layer_, RestoreData{current_layer_ - 1}}); tracker_.restore(); current_layer_--; // Must go here; func params order of eval is undefined } // clang-format off // 2x3 2D affine subset of a 4x4 transform in row major order void MockCanvas::Transform2DAffine(SkScalar mxx, SkScalar mxy, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myt) { Transform(SkMatrix::MakeAll(mxx, mxy, mxt, myx, myy, myt, 0, 0, 1)); } // full 4x4 transform in row major order void MockCanvas::TransformFullPerspective( SkScalar mxx, SkScalar mxy, SkScalar mxz, SkScalar mxt, SkScalar myx, SkScalar myy, SkScalar myz, SkScalar myt, SkScalar mzx, SkScalar mzy, SkScalar mzz, SkScalar mzt, SkScalar mwx, SkScalar mwy, SkScalar mwz, SkScalar mwt) { Transform(SkM44(mxx, mxy, mxz, mxt, myx, myy, myz, myt, mzx, mzy, mzz, mzt, mwx, mwy, mwz, mwt)); } // clang-format on void MockCanvas::Transform(const SkMatrix* matrix) { draw_calls_.emplace_back( DrawCall{current_layer_, ConcatMatrixData{SkM44(*matrix)}}); tracker_.transform(*matrix); } void MockCanvas::Transform(const SkM44* matrix) { draw_calls_.emplace_back(DrawCall{current_layer_, ConcatMatrixData{*matrix}}); tracker_.transform(*matrix); } void MockCanvas::SetTransform(const SkMatrix* matrix) { draw_calls_.emplace_back( DrawCall{current_layer_, SetMatrixData{SkM44(*matrix)}}); tracker_.setTransform(*matrix); } void MockCanvas::SetTransform(const SkM44* matrix) { draw_calls_.emplace_back(DrawCall{current_layer_, SetMatrixData{*matrix}}); tracker_.setTransform(*matrix); } void MockCanvas::TransformReset() { draw_calls_.emplace_back(DrawCall{current_layer_, SetMatrixData{SkM44()}}); tracker_.setIdentity(); } void MockCanvas::Translate(SkScalar x, SkScalar y) { this->Transform(SkM44::Translate(x, y)); } void MockCanvas::Scale(SkScalar x, SkScalar y) { this->Transform(SkM44::Scale(x, y)); } void MockCanvas::Rotate(SkScalar degrees) { this->Transform(SkMatrix::RotateDeg(degrees)); } void MockCanvas::Skew(SkScalar sx, SkScalar sy) { this->Transform(SkMatrix::Skew(sx, sy)); } SkM44 MockCanvas::GetTransformFullPerspective() const { return tracker_.matrix_4x4(); } SkMatrix MockCanvas::GetTransform() const { return tracker_.matrix_3x3(); } void MockCanvas::DrawTextBlob(const sk_sp<SkTextBlob>& text, SkScalar x, SkScalar y, const DlPaint& paint) { // This duplicates existing logic in SkCanvas::onDrawPicture // that should probably be split out so it doesn't need to be here as well. // SkRect storage; // if (paint.canComputeFastBounds()) { // storage = text->bounds().makeOffset(x, y); // SkRect tmp; // if (this->quickReject(paint.computeFastBounds(storage, &tmp))) { // return; // } // } draw_calls_.emplace_back(DrawCall{ current_layer_, DrawTextData{text ? text->serialize(SkSerialProcs{}) : SkData::MakeUninitialized(0), paint, SkPoint::Make(x, y)}}); } void MockCanvas::DrawTextFrame( const std::shared_ptr<impeller::TextFrame>& text_frame, SkScalar x, SkScalar y, const DlPaint& paint) { FML_DCHECK(false); } void MockCanvas::DrawRect(const SkRect& rect, const DlPaint& paint) { draw_calls_.emplace_back(DrawCall{current_layer_, DrawRectData{rect, paint}}); } void MockCanvas::DrawPath(const SkPath& path, const DlPaint& paint) { draw_calls_.emplace_back(DrawCall{current_layer_, DrawPathData{path, paint}}); } void MockCanvas::DrawShadow(const SkPath& path, const DlColor color, const SkScalar elevation, bool transparent_occluder, SkScalar dpr) { draw_calls_.emplace_back(DrawCall{ current_layer_, DrawShadowData{path, color, elevation, transparent_occluder, dpr}}); } void MockCanvas::DrawImage(const sk_sp<DlImage>& image, SkPoint point, const DlImageSampling options, const DlPaint* paint) { if (paint) { draw_calls_.emplace_back( DrawCall{current_layer_, DrawImageData{image, point.fX, point.fY, options, *paint}}); } else { draw_calls_.emplace_back( DrawCall{current_layer_, DrawImageDataNoPaint{image, point.fX, point.fY, options}}); } } void MockCanvas::DrawDisplayList(const sk_sp<DisplayList> display_list, SkScalar opacity) { draw_calls_.emplace_back( DrawCall{current_layer_, DrawDisplayListData{display_list, opacity}}); } void MockCanvas::ClipRect(const SkRect& rect, ClipOp op, bool is_aa) { ClipEdgeStyle style = is_aa ? kSoftClipEdgeStyle : kHardClipEdgeStyle; draw_calls_.emplace_back( DrawCall{current_layer_, ClipRectData{rect, op, style}}); tracker_.clipRect(rect, op, is_aa); } void MockCanvas::ClipRRect(const SkRRect& rrect, ClipOp op, bool is_aa) { ClipEdgeStyle style = is_aa ? kSoftClipEdgeStyle : kHardClipEdgeStyle; draw_calls_.emplace_back( DrawCall{current_layer_, ClipRRectData{rrect, op, style}}); tracker_.clipRRect(rrect, op, is_aa); } void MockCanvas::ClipPath(const SkPath& path, ClipOp op, bool is_aa) { ClipEdgeStyle style = is_aa ? kSoftClipEdgeStyle : kHardClipEdgeStyle; draw_calls_.emplace_back( DrawCall{current_layer_, ClipPathData{path, op, style}}); tracker_.clipPath(path, op, is_aa); } SkRect MockCanvas::GetDestinationClipBounds() const { return tracker_.device_cull_rect(); } SkRect MockCanvas::GetLocalClipBounds() const { return tracker_.local_cull_rect(); } bool MockCanvas::QuickReject(const SkRect& bounds) const { return tracker_.content_culled(bounds); } void MockCanvas::DrawDRRect(const SkRRect&, const SkRRect&, const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawPaint(const DlPaint& paint) { draw_calls_.emplace_back(DrawCall{current_layer_, DrawPaintData{paint}}); } void MockCanvas::DrawColor(DlColor color, DlBlendMode mode) { DrawPaint(DlPaint(color).setBlendMode(mode)); } void MockCanvas::DrawLine(const SkPoint& p0, const SkPoint& p1, const DlPaint& paint) { FML_DCHECK(false); } void MockCanvas::DrawPoints(PointMode, uint32_t, const SkPoint[], const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawOval(const SkRect&, const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawCircle(const SkPoint& center, SkScalar radius, const DlPaint& paint) { FML_DCHECK(false); } void MockCanvas::DrawArc(const SkRect&, SkScalar, SkScalar, bool, const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawRRect(const SkRRect&, const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawImageRect(const sk_sp<DlImage>&, const SkRect&, const SkRect&, const DlImageSampling, const DlPaint*, SrcRectConstraint constraint) { FML_DCHECK(false); } void MockCanvas::DrawImageNine(const sk_sp<DlImage>& image, const SkIRect& center, const SkRect& dst, DlFilterMode filter, const DlPaint* paint) { FML_DCHECK(false); } void MockCanvas::DrawVertices(const DlVertices*, DlBlendMode, const DlPaint&) { FML_DCHECK(false); } void MockCanvas::DrawAtlas(const sk_sp<DlImage>&, const SkRSXform[], const SkRect[], const DlColor[], int, DlBlendMode, const DlImageSampling, const SkRect*, const DlPaint*) { FML_DCHECK(false); } void MockCanvas::Flush() { FML_DCHECK(false); } // -------------------------------------------------------- // A few ostream operators duplicated from assertions_skia.cc // In the short term, there are issues trying to include that file // here because it appears in a skia-targeted testing source set // and in the long term, DlCanvas, and therefore this file will // eventually be cleaned of these SkObject dependencies and these // ostream operators will be converted to their DL equivalents. static std::ostream& operator<<(std::ostream& os, const SkPoint& r) { return os << "XY: " << r.fX << ", " << r.fY; } static std::ostream& operator<<(std::ostream& os, const SkRect& r) { return os << "LTRB: " << r.fLeft << ", " << r.fTop << ", " << r.fRight << ", " << r.fBottom; } static std::ostream& operator<<(std::ostream& os, const SkRRect& r) { return os << "LTRB: " << r.rect().fLeft << ", " << r.rect().fTop << ", " << r.rect().fRight << ", " << r.rect().fBottom; } static std::ostream& operator<<(std::ostream& os, const SkPath& r) { return os << "Valid: " << r.isValid() << ", FillType: " << static_cast<int>(r.getFillType()) << ", Bounds: " << r.getBounds(); } // -------------------------------------------------------- static std::ostream& operator<<(std::ostream& os, const SkM44& m) { os << m.rc(0, 0) << ", " << m.rc(0, 1) << ", " << m.rc(0, 2) << ", " << m.rc(0, 3) << std::endl; os << m.rc(1, 0) << ", " << m.rc(1, 1) << ", " << m.rc(1, 2) << ", " << m.rc(1, 3) << std::endl; os << m.rc(2, 0) << ", " << m.rc(2, 1) << ", " << m.rc(2, 2) << ", " << m.rc(2, 3) << std::endl; os << m.rc(3, 0) << ", " << m.rc(3, 1) << ", " << m.rc(3, 2) << ", " << m.rc(3, 3); return os; } bool operator==(const MockCanvas::SaveData& a, const MockCanvas::SaveData& b) { return a.save_to_layer == b.save_to_layer; } std::ostream& operator<<(std::ostream& os, const MockCanvas::SaveData& data) { return os << data.save_to_layer; } bool operator==(const MockCanvas::SaveLayerData& a, const MockCanvas::SaveLayerData& b) { return a.save_bounds == b.save_bounds && a.restore_paint == b.restore_paint && Equals(a.backdrop_filter, b.backdrop_filter) && a.save_to_layer == b.save_to_layer; } std::ostream& operator<<(std::ostream& os, const MockCanvas::SaveLayerData& data) { return os << data.save_bounds << " " << data.restore_paint << " " << data.backdrop_filter << " " << data.save_to_layer; } bool operator==(const MockCanvas::RestoreData& a, const MockCanvas::RestoreData& b) { return a.restore_to_layer == b.restore_to_layer; } std::ostream& operator<<(std::ostream& os, const MockCanvas::RestoreData& data) { return os << data.restore_to_layer; } bool operator==(const MockCanvas::ConcatMatrixData& a, const MockCanvas::ConcatMatrixData& b) { return a.matrix == b.matrix; } std::ostream& operator<<(std::ostream& os, const MockCanvas::ConcatMatrixData& data) { return os << data.matrix; } bool operator==(const MockCanvas::SetMatrixData& a, const MockCanvas::SetMatrixData& b) { return a.matrix == b.matrix; } std::ostream& operator<<(std::ostream& os, const MockCanvas::SetMatrixData& data) { return os << data.matrix; } bool operator==(const MockCanvas::DrawRectData& a, const MockCanvas::DrawRectData& b) { return a.rect == b.rect && a.paint == b.paint; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawRectData& data) { return os << data.rect << " " << data.paint; } bool operator==(const MockCanvas::DrawPathData& a, const MockCanvas::DrawPathData& b) { return a.path == b.path && a.paint == b.paint; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawPathData& data) { return os << data.path << " " << data.paint; } bool operator==(const MockCanvas::DrawTextData& a, const MockCanvas::DrawTextData& b) { return a.serialized_text->equals(b.serialized_text.get()) && a.paint == b.paint && a.offset == b.offset; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawTextData& data) { return os << data.serialized_text << " " << data.paint << " " << data.offset; } bool operator==(const MockCanvas::DrawImageData& a, const MockCanvas::DrawImageData& b) { return a.image == b.image && a.x == b.x && a.y == b.y && a.options == b.options && a.paint == b.paint; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawImageData& data) { return os << data.image << " " << data.x << " " << data.y << " " << data.options << " " << data.paint; } bool operator==(const MockCanvas::DrawImageDataNoPaint& a, const MockCanvas::DrawImageDataNoPaint& b) { return a.image == b.image && a.x == b.x && a.y == b.y && a.options == b.options; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawImageDataNoPaint& data) { return os << data.image << " " << data.x << " " << data.y << " " << data.options; } bool operator==(const MockCanvas::DrawDisplayListData& a, const MockCanvas::DrawDisplayListData& b) { return a.display_list->Equals(b.display_list) && a.opacity == b.opacity; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawDisplayListData& data) { auto dl = data.display_list; return os << "[" << dl->unique_id() << " " << dl->op_count() << " " << dl->bytes() << "] " << data.opacity; } bool operator==(const MockCanvas::DrawShadowData& a, const MockCanvas::DrawShadowData& b) { return a.path == b.path && a.color == b.color && a.elevation == b.elevation && a.transparent_occluder == b.transparent_occluder && a.dpr == b.dpr; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawShadowData& data) { return os << data.path << " " << data.color << " " << data.elevation << " " << data.transparent_occluder << " " << data.dpr; } bool operator==(const MockCanvas::ClipRectData& a, const MockCanvas::ClipRectData& b) { return a.rect == b.rect && a.clip_op == b.clip_op && a.style == b.style; } static std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipEdgeStyle& style) { return os << (style == MockCanvas::kSoftClipEdgeStyle ? "kSoftEdges" : "kHardEdges"); } std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipRectData& data) { return os << data.rect << " " << data.clip_op << " " << data.style; } bool operator==(const MockCanvas::ClipRRectData& a, const MockCanvas::ClipRRectData& b) { return a.rrect == b.rrect && a.clip_op == b.clip_op && a.style == b.style; } std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipRRectData& data) { return os << data.rrect << " " << data.clip_op << " " << data.style; } bool operator==(const MockCanvas::ClipPathData& a, const MockCanvas::ClipPathData& b) { return a.path == b.path && a.clip_op == b.clip_op && a.style == b.style; } std::ostream& operator<<(std::ostream& os, const MockCanvas::ClipPathData& data) { return os << data.path << " " << data.clip_op << " " << data.style; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawCallData& data) { std::visit([&os](auto& d) { os << d; }, data); return os; } bool operator==(const MockCanvas::DrawCall& a, const MockCanvas::DrawCall& b) { return a.layer == b.layer && a.data == b.data; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawCall& draw) { return os << "[Layer: " << draw.layer << ", Data: " << draw.data << "]"; } bool operator==(const MockCanvas::DrawPaintData& a, const MockCanvas::DrawPaintData& b) { return a.paint == b.paint; } std::ostream& operator<<(std::ostream& os, const MockCanvas::DrawPaintData& data) { return os << data.paint; } } // namespace testing } // namespace flutter
engine/testing/mock_canvas.cc/0
{ "file_path": "engine/testing/mock_canvas.cc", "repo_id": "engine", "token_count": 8537 }
378
# 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/rules/runtime_mode.gni") template("gradle_task") { action(target_name) { assert(defined(invoker.task), "task is a required parmaeter") assert(defined(invoker.outputs), "outputs is a required parameter") assert(defined(invoker.sources), "sources is a required parameter") assert(defined(invoker.gradle_project_dir), "gradle_project_dir is required (normally: rebase_path(\".\"") assert(defined(invoker.app_name), "app_name is a required parameter") script = "//flutter/testing/rules/run_gradle.py" inputs = [ "$root_out_dir/flutter.jar" ] sources = invoker.sources outputs = invoker.outputs out_dir = rebase_path("$root_out_dir/${invoker.app_name}") args = [ invoker.gradle_project_dir, invoker.task, "--no-daemon", "-Pflutter_jar=" + rebase_path("$root_out_dir/flutter.jar"), "-Pout_dir=$out_dir", "--project-cache-dir=$out_dir/.gradle", "--gradle-user-home=$out_dir/.gradle", ] if (is_aot) { args += [ "-Plibapp=" + rebase_path("$target_gen_dir/libs") ] inputs += [ "$target_gen_dir/libs/$android_app_abi/libapp.so" ] } deps = [ "//flutter/shell/platform/android:android_jar" ] if (defined(invoker.deps)) { deps += invoker.deps } } }
engine/testing/rules/android.gni/0
{ "file_path": "engine/testing/rules/android.gni", "repo_id": "engine", "token_count": 596 }
379
// 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. package dev.flutter.scenariosui; import android.content.Intent; import androidx.annotation.NonNull; import androidx.test.filters.LargeTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import dev.flutter.scenarios.SpawnMultiEngineActivity; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) @LargeTest public class SpawnMultiEngineTest { Intent intent; @Rule @NonNull public ActivityTestRule<SpawnMultiEngineActivity> activityRule = new ActivityTestRule<>( SpawnMultiEngineActivity.class, /*initialTouchMode=*/ false, /*launchActivity=*/ false); @Before public void setUp() { intent = new Intent(Intent.ACTION_MAIN); } @Test public void testSpawnedEngine() throws Exception { activityRule.launchActivity(intent); } }
engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/SpawnMultiEngineTest.java/0
{ "file_path": "engine/testing/scenario_app/android/app/src/androidTest/java/dev/flutter/scenariosui/SpawnMultiEngineTest.java", "repo_id": "engine", "token_count": 331 }
380
<?xml version="1.0" encoding="utf-8"?> <!-- Exclude all files from backup --> <data-extraction-rules> <cloud-backup> <exclude domain="root" path="."/> <exclude domain="file" path="."/> <exclude domain="database" path="."/> <exclude domain="sharedpref" path="."/> <exclude domain="external" path="."/> </cloud-backup> <device-transfer> <exclude domain="root" path="."/> <exclude domain="file" path="."/> <exclude domain="database" path="."/> <exclude domain="sharedpref" path="."/> <exclude domain="external" path="."/> </device-transfer> </data-extraction-rules>
engine/testing/scenario_app/android/app/src/main/res/xml/data_extraction_rules.xml/0
{ "file_path": "engine/testing/scenario_app/android/app/src/main/res/xml/data_extraction_rules.xml", "repo_id": "engine", "token_count": 275 }
381
// 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 "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; UIButton* openShare = [UIButton systemButtonWithPrimaryAction:[UIAction actionWithHandler:^( __kindof UIAction* _Nonnull action) { UIActivityViewController* activityVC = [[UIActivityViewController alloc] initWithActivityItems:@[ @"text to share" ] applicationActivities:nil]; activityVC.excludedActivityTypes = @[ UIActivityTypePrint, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll ]; // Exclude whichever aren't relevant [self presentViewController:activityVC animated:YES completion:nil]; }]]; openShare.backgroundColor = [UIColor systemPinkColor]; [openShare setTitle:@"Open Share" forState:UIControlStateNormal]; [self.view addSubview:openShare]; openShare.frame = CGRectMake(0, 0, 200, 200); } @end
engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/ViewController.m/0
{ "file_path": "engine/testing/scenario_app/ios/FlutterAppExtensionTestHost/FlutterAppExtensionTestHost/ViewController.m", "repo_id": "engine", "token_count": 589 }
382
// 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. #import "AppDelegate.h" #import "ContinuousTexture.h" #import "FlutterEngine+ScenariosTest.h" #import "ScreenBeforeFlutter.h" #import "TextPlatformView.h" // A UIViewController that sets YES for its preferedStatusBarHidden property. // StatusBar includes current time, which is non-deterministic. This ViewController // removes the StatusBar to make the screenshot deterministic. @interface NoStatusBarViewController : UIViewController @end @implementation NoStatusBarViewController - (BOOL)prefersStatusBarHidden { return YES; } @end // The FlutterViewController version of NoStatusBarViewController @interface NoStatusBarFlutterViewController : FlutterViewController @end @implementation NoStatusBarFlutterViewController - (BOOL)prefersStatusBarHidden { return YES; } @end @implementation AppDelegate - (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--maskview-blocking"]) { self.window.tintColor = UIColor.systemPinkColor; } NSDictionary<NSString*, NSString*>* launchArgsMap = @{ // The golden test args should match `GoldenTestManager`. @"--locale-initialization" : @"locale_initialization", @"--platform-view" : @"platform_view", @"--platform-view-no-overlay-intersection" : @"platform_view_no_overlay_intersection", @"--platform-view-two-intersecting-overlays" : @"platform_view_two_intersecting_overlays", @"--platform-view-partial-intersection" : @"platform_view_partial_intersection", @"--platform-view-one-overlay-two-intersecting-overlays" : @"platform_view_one_overlay_two_intersecting_overlays", @"--platform-view-multiple-without-overlays" : @"platform_view_multiple_without_overlays", @"--platform-view-max-overlays" : @"platform_view_max_overlays", @"--platform-view-multiple" : @"platform_view_multiple", @"--platform-view-multiple-background-foreground" : @"platform_view_multiple_background_foreground", @"--platform-view-cliprect" : @"platform_view_cliprect", @"--platform-view-cliprrect" : @"platform_view_cliprrect", @"--platform-view-large-cliprrect" : @"platform_view_large_cliprrect", @"--platform-view-clippath" : @"platform_view_clippath", @"--platform-view-cliprrect-with-transform" : @"platform_view_cliprrect_with_transform", @"--platform-view-large-cliprrect-with-transform" : @"platform_view_large_cliprrect_with_transform", @"--platform-view-cliprect-with-transform" : @"platform_view_cliprect_with_transform", @"--platform-view-clippath-with-transform" : @"platform_view_clippath_with_transform", @"--platform-view-transform" : @"platform_view_transform", @"--platform-view-opacity" : @"platform_view_opacity", @"--platform-view-with-other-backdrop-filter" : @"platform_view_with_other_backdrop_filter", @"--two-platform-views-with-other-backdrop-filter" : @"two_platform_views_with_other_backdrop_filter", @"--platform-view-with-negative-backdrop-filter" : @"platform_view_with_negative_backdrop_filter", @"--platform-view-rotate" : @"platform_view_rotate", @"--non-full-screen-flutter-view-platform-view" : @"non_full_screen_flutter_view_platform_view", @"--gesture-reject-after-touches-ended" : @"platform_view_gesture_reject_after_touches_ended", @"--gesture-reject-eager" : @"platform_view_gesture_reject_eager", @"--gesture-accept" : @"platform_view_gesture_accept", @"--gesture-accept-with-overlapping-platform-views" : @"platform_view_gesture_accept_with_overlapping_platform_views", @"--tap-status-bar" : @"tap_status_bar", @"--animated-color-square" : @"animated_color_square", @"--solid-blue" : @"solid_blue", @"--platform-view-with-continuous-texture" : @"platform_view_with_continuous_texture", @"--bogus-font-text" : @"bogus_font_text", @"--spawn-engine-works" : @"spawn_engine_works", @"--pointer-events" : @"pointer_events", @"--platform-view-scrolling-under-widget" : @"platform_view_scrolling_under_widget", @"--platform-views-with-clips-scrolling" : @"platform_views_with_clips_scrolling", @"--platform-view-cliprect-after-moved" : @"platform_view_cliprect_after_moved", @"--two-platform-view-clip-rect" : @"two_platform_view_clip_rect", @"--two-platform-view-clip-rrect" : @"two_platform_view_clip_rrect", @"--two-platform-view-clip-path" : @"two_platform_view_clip_path", @"--darwin-system-font" : @"darwin_system_font", }; __block NSString* flutterViewControllerTestName = nil; [launchArgsMap enumerateKeysAndObjectsUsingBlock:^(NSString* argument, NSString* testName, BOOL* stop) { if ([[[NSProcessInfo processInfo] arguments] containsObject:argument]) { flutterViewControllerTestName = testName; *stop = YES; } }]; if (flutterViewControllerTestName) { [self setupFlutterViewControllerTest:flutterViewControllerTestName]; } else if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--screen-before-flutter"]) { self.window.rootViewController = [[ScreenBeforeFlutter alloc] initWithEngineRunCompletion:nil]; } else { self.window.rootViewController = [[UIViewController alloc] init]; } [self.window makeKeyAndVisible]; if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--with-continuous-texture"]) { [ContinuousTexture registerWithRegistrar:[self registrarForPlugin:@"com.constant.firing.texture"]]; } return [super application:application didFinishLaunchingWithOptions:launchOptions]; } - (FlutterEngine*)engineForTest:(NSString*)scenarioIdentifier { if ([scenarioIdentifier isEqualToString:@"spawn_engine_works"]) { FlutterEngine* spawner = [[FlutterEngine alloc] initWithName:@"FlutterControllerTest" project:nil]; [spawner run]; return [spawner spawnWithEntrypoint:nil libraryURI:nil initialRoute:nil entrypointArgs:nil]; } else { FlutterEngine* engine = [[FlutterEngine alloc] initWithName:@"FlutterControllerTest" project:nil]; [engine run]; return engine; } } - (FlutterViewController*)flutterViewControllerForTest:(NSString*)scenarioIdentifier withEngine:(FlutterEngine*)engine { if ([scenarioIdentifier isEqualToString:@"tap_status_bar"]) { return [[FlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; } else { return [[NoStatusBarFlutterViewController alloc] initWithEngine:engine nibName:nil bundle:nil]; } } - (void)setupFlutterViewControllerTest:(NSString*)scenarioIdentifier { FlutterEngine* engine = [self engineForTest:scenarioIdentifier]; FlutterViewController* flutterViewController = [self flutterViewControllerForTest:scenarioIdentifier withEngine:engine]; flutterViewController.view.accessibilityIdentifier = @"flutter_view"; [engine.binaryMessenger setMessageHandlerOnChannel:@"waiting_for_status" binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply) { FlutterMethodChannel* channel = [FlutterMethodChannel methodChannelWithName:@"driver" binaryMessenger:engine.binaryMessenger codec:[FlutterJSONMethodCodec sharedInstance]]; [channel invokeMethod:@"set_scenario" arguments:@{@"name" : scenarioIdentifier}]; }]; // Can be used to synchronize timing in the test for a signal from Dart. [engine.binaryMessenger setMessageHandlerOnChannel:@"display_data" binaryMessageHandler:^(NSData* _Nullable message, FlutterBinaryReply _Nonnull reply) { NSDictionary* dict = [NSJSONSerialization JSONObjectWithData:message options:0 error:nil]; UITextField* text = [[UITextField alloc] initWithFrame:CGRectMake(0, 400, 300, 100)]; text.text = dict[@"data"]; [flutterViewController.view addSubview:text]; }]; TextPlatformViewFactory* textPlatformViewFactory = [[TextPlatformViewFactory alloc] initWithMessenger:engine.binaryMessenger]; NSObject<FlutterPluginRegistrar>* registrar = [engine registrarForPlugin:@"scenarios/TextPlatformViewPlugin"]; [registrar registerViewFactory:textPlatformViewFactory withId:@"scenarios/textPlatformView" gestureRecognizersBlockingPolicy:FlutterPlatformViewGestureRecognizersBlockingPolicyEager]; [registrar registerViewFactory:textPlatformViewFactory withId:@"scenarios/textPlatformView_blockPolicyUntilTouchesEnded" gestureRecognizersBlockingPolicy: FlutterPlatformViewGestureRecognizersBlockingPolicyWaitUntilTouchesEnded]; UIViewController* rootViewController = flutterViewController; // Make Flutter View's origin x/y not 0. if ([scenarioIdentifier isEqualToString:@"non_full_screen_flutter_view_platform_view"]) { rootViewController = [[NoStatusBarViewController alloc] init]; [rootViewController.view addSubview:flutterViewController.view]; flutterViewController.view.frame = CGRectMake(150, 150, 500, 500); } self.window.rootViewController = rootViewController; if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--assert-ca-layer-type"]) { if ([[[NSProcessInfo processInfo] arguments] containsObject:@"--enable-software-rendering"]) { NSAssert([flutterViewController.view.layer isKindOfClass:[CALayer class]], @"Expected CALayer for software rendering."); } else { NSAssert([flutterViewController.view.layer isKindOfClass:[CAMetalLayer class]], @"Expected CAMetalLayer for non-software rendering."); } } } @end
engine/testing/scenario_app/ios/Scenarios/Scenarios/AppDelegate.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/Scenarios/AppDelegate.m", "repo_id": "engine", "token_count": 3901 }
383
// 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_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSSHARE_SHAREVIEWCONTROLLER_H_ #define FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSSHARE_SHAREVIEWCONTROLLER_H_ #import <Flutter/Flutter.h> #import <UIKit/UIKit.h> @interface ShareViewController : FlutterViewController @end #endif // FLUTTER_TESTING_SCENARIO_APP_IOS_SCENARIOS_SCENARIOSSHARE_SHAREVIEWCONTROLLER_H_
engine/testing/scenario_app/ios/Scenarios/ScenariosShare/ShareViewController.h/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosShare/ShareViewController.h", "repo_id": "engine", "token_count": 214 }
384
// 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 "GoldenTestManager.h" #import <XCTest/XCTest.h> @interface GoldenTestManager () @property(readwrite, strong, nonatomic) GoldenImage* goldenImage; @end @implementation GoldenTestManager NSDictionary* launchArgsMap; const double kDefaultRmseThreshold = 0.5; - (instancetype)initWithLaunchArg:(NSString*)launchArg { self = [super init]; if (self) { // The launchArgsMap should match the one in the `PlatformVieGoldenTestManager`. static NSDictionary<NSString*, NSString*>* launchArgsMap; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ launchArgsMap = @{ @"--platform-view" : @"platform_view", @"--platform-view-multiple" : @"platform_view_multiple", @"--platform-view-multiple-background-foreground" : @"platform_view_multiple_background_foreground", @"--platform-view-cliprect" : @"platform_view_cliprect", @"--platform-view-cliprrect" : @"platform_view_cliprrect", @"--platform-view-large-cliprrect" : @"platform_view_large_cliprrect", @"--platform-view-clippath" : @"platform_view_clippath", @"--platform-view-cliprrect-with-transform" : @"platform_view_cliprrect_with_transform", @"--platform-view-large-cliprrect-with-transform" : @"platform_view_large_cliprrect_with_transform", @"--platform-view-cliprect-with-transform" : @"platform_view_cliprect_with_transform", @"--platform-view-clippath-with-transform" : @"platform_view_clippath_with_transform", @"--platform-view-transform" : @"platform_view_transform", @"--platform-view-opacity" : @"platform_view_opacity", @"--platform-view-with-other-backdrop-filter" : @"platform_view_with_other_backdrop_filter", @"--two-platform-views-with-other-backdrop-filter" : @"two_platform_views_with_other_backdrop_filter", @"--platform-view-with-negative-backdrop-filter" : @"platform_view_with_negative_backdrop_filter", @"--platform-view-rotate" : @"platform_view_rotate", @"--non-full-screen-flutter-view-platform-view" : @"non_full_screen_flutter_view_platform_view", @"--bogus-font-text" : @"bogus_font_text", @"--spawn-engine-works" : @"spawn_engine_works", @"--platform-view-cliprect-after-moved" : @"platform_view_cliprect_after_moved", @"--two-platform-view-clip-rect" : @"two_platform_view_clip_rect", @"--two-platform-view-clip-rrect" : @"two_platform_view_clip_rrect", @"--two-platform-view-clip-path" : @"two_platform_view_clip_path", @"--app-extension" : @"app_extension", @"--darwin-system-font" : @"darwin_system_font", }; }); _identifier = launchArgsMap[launchArg]; NSString* impeller = @""; NSNumber* enableImpeller = [[NSBundle bundleWithIdentifier:@"dev.flutter.ScenariosUITests"] objectForInfoDictionaryKey:@"FLTEnableImpeller"]; if (enableImpeller != nil) { impeller = enableImpeller.boolValue ? @"impeller_" : @""; } else { NSLog(@"FLTEnableImpeller was nil"); } NSLog(@"impeller = '%@'", impeller); NSString* prefix = [NSString stringWithFormat:@"golden_%@_%@", _identifier, impeller]; _goldenImage = [[GoldenImage alloc] initWithGoldenNamePrefix:prefix]; _launchArg = launchArg; } return self; } - (void)checkGoldenForTest:(XCTestCase*)test rmesThreshold:(double)rmesThreshold { XCUIScreenshot* screenshot = [[XCUIScreen mainScreen] screenshot]; if (!_goldenImage.image) { XCTAttachment* attachment = [XCTAttachment attachmentWithScreenshot:screenshot]; attachment.name = [_goldenImage.goldenName stringByAppendingString:@"_new.png"]; attachment.lifetime = XCTAttachmentLifetimeKeepAlways; [test addAttachment:attachment]; // Instead of XCTFail because that definition changed between Xcode 11 and 12 whereas this impl // is stable. _XCTPrimitiveFail(test, @"This test will fail - no golden named %@ found. " @"Follow the steps in the README to add a new golden.", _goldenImage.goldenName); } if (![_goldenImage compareGoldenToImage:screenshot.image rmesThreshold:rmesThreshold]) { XCTAttachment* screenshotAttachment = [XCTAttachment attachmentWithImage:screenshot.image]; screenshotAttachment.name = [_goldenImage.goldenName stringByAppendingString:@"_actual.png"]; screenshotAttachment.lifetime = XCTAttachmentLifetimeKeepAlways; [test addAttachment:screenshotAttachment]; _XCTPrimitiveFail(test, @"Goldens do not match. Follow the steps in the " @"README to update golden named %@ if needed.", _goldenImage.goldenName); } } @end
engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenTestManager.m/0
{ "file_path": "engine/testing/scenario_app/ios/Scenarios/ScenariosUITests/GoldenTestManager.m", "repo_id": "engine", "token_count": 1989 }
385
// 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:vector_math/vector_math_64.dart'; import 'scenario.dart'; /// Sends the received locale data back as semantics information. class LocaleInitialization extends Scenario { /// Constructor LocaleInitialization(super.view); int _tapCount = 0; /// Start off by sending the supported locales list via semantics. @override void onBeginFrame(Duration duration) { // Doesn't matter what we draw. Just paint white. final SceneBuilder builder = SceneBuilder(); final PictureRecorder recorder = PictureRecorder(); final Canvas canvas = Canvas(recorder); canvas.drawRect( Rect.fromLTWH(0, 0, view.physicalSize.width, view.physicalSize.height), Paint()..color = const Color.fromARGB(255, 255, 255, 255), ); final Picture picture = recorder.endRecording(); builder.addPicture( Offset.zero, picture, ); final Scene scene = builder.build(); view.render(scene); scene.dispose(); // On the first frame, pretend that it drew a text field. Send the // corresponding semantics tree comprised of 1 node with the locale data // as the label. final SemanticsUpdateBuilder semanticsUpdateBuilder = SemanticsUpdateBuilder()..updateNode( id: 0, // SemanticsFlag.isTextField. flags: 16, // SemanticsAction.tap. actions: 1, rect: const Rect.fromLTRB(0.0, 0.0, 414.0, 48.0), identifier: '', label: view.platformDispatcher.locales.toString(), labelAttributes: <StringAttribute>[], textDirection: TextDirection.ltr, textSelectionBase: -1, textSelectionExtent: -1, platformViewId: -1, maxValueLength: -1, currentValueLength: 0, scrollChildren: 0, scrollIndex: 0, scrollPosition: 0.0, scrollExtentMax: 0.0, scrollExtentMin: 0.0, transform: Matrix4.identity().storage, elevation: 0.0, thickness: 0.0, hint: '', hintAttributes: <StringAttribute>[], value: '', valueAttributes: <StringAttribute>[], increasedValue: '', increasedValueAttributes: <StringAttribute>[], decreasedValue: '', decreasedValueAttributes: <StringAttribute>[], tooltip: '', childrenInTraversalOrder: Int32List(0), childrenInHitTestOrder: Int32List(0), additionalActions: Int32List(0), ); final SemanticsUpdate semanticsUpdate = semanticsUpdateBuilder.build(); view.updateSemantics(semanticsUpdate); } /// Handle taps. /// /// Send changing information via semantics on each successive tap. @override void onPointerDataPacket(PointerDataPacket packet) { String label = ''; switch(_tapCount) { case 1: { // Set label to string data we wish to pass on first frame. label = '1'; break; } // Expand for other test cases. } final SemanticsUpdateBuilder semanticsUpdateBuilder = SemanticsUpdateBuilder()..updateNode( id: 0, // SemanticsFlag.isTextField. flags: 16, // SemanticsAction.tap. actions: 1, rect: const Rect.fromLTRB(0.0, 0.0, 414.0, 48.0), identifier: '', label: label, labelAttributes: <StringAttribute>[], textDirection: TextDirection.ltr, textSelectionBase: 0, textSelectionExtent: 0, platformViewId: -1, maxValueLength: -1, currentValueLength: 0, scrollChildren: 0, scrollIndex: 0, scrollPosition: 0.0, scrollExtentMax: 0.0, scrollExtentMin: 0.0, transform: Matrix4.identity().storage, elevation: 0.0, thickness: 0.0, hint: '', hintAttributes: <StringAttribute>[], value: '', valueAttributes: <StringAttribute>[], increasedValue: '', increasedValueAttributes: <StringAttribute>[], decreasedValue: '', decreasedValueAttributes: <StringAttribute>[], tooltip: '', childrenInTraversalOrder: Int32List(0), childrenInHitTestOrder: Int32List(0), additionalActions: Int32List(0), ); final SemanticsUpdate semanticsUpdate = semanticsUpdateBuilder.build(); view.updateSemantics(semanticsUpdate); _tapCount++; } }
engine/testing/scenario_app/lib/src/locale_initialization.dart/0
{ "file_path": "engine/testing/scenario_app/lib/src/locale_initialization.dart", "repo_id": "engine", "token_count": 1813 }
386
# 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. name: skia_gold_client publish_to: none environment: sdk: '>=3.2.0-0 <4.0.0' # Do not add any dependencies that require more than what is provided in # //third_party/dart/pkg, //third_party/dart/third_party/pkg, or # //third_party/pkg. In particular, package:test is not usable here. # If you do add packages here, make sure you can run `pub get --offline`, and # check the .packages and .package_config to make sure all the paths are # relative to this directory into //third_party/dart, or //third_party/pkg dependencies: crypto: any meta: any path: any engine_repo_tools: any process: any dev_dependencies: args: any git_repo_tools: any litetest: any process_fakes: any dependency_overrides: args: path: ../../../third_party/dart/third_party/pkg/args async: path: ../../../third_party/dart/third_party/pkg/async async_helper: path: ../../../third_party/dart/pkg/async_helper collection: path: ../../../third_party/dart/third_party/pkg/collection crypto: path: ../../../third_party/dart/third_party/pkg/crypto engine_repo_tools: path: ../../tools/pkg/engine_repo_tools expect: path: ../../../third_party/dart/pkg/expect file: path: ../../../third_party/dart/third_party/pkg/file/packages/file git_repo_tools: path: ../../tools/pkg/git_repo_tools litetest: path: ../../testing/litetest meta: path: ../../../third_party/dart/pkg/meta path: path: ../../../third_party/dart/third_party/pkg/path platform: path: ../../third_party/pkg/platform process: path: ../../third_party/pkg/process process_fakes: path: ../../tools/pkg/process_fakes process_runner: path: ../../third_party/pkg/process_runner smith: path: ../../../third_party/dart/pkg/smith typed_data: path: ../../../third_party/dart/third_party/pkg/typed_data
engine/testing/skia_gold_client/pubspec.yaml/0
{ "file_path": "engine/testing/skia_gold_client/pubspec.yaml", "repo_id": "engine", "token_count": 765 }
387
// 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:path/path.dart' as p; // This script verifies that the release binaries only export the expected // symbols. // // Android binaries (libflutter.so) should only export one symbol "JNI_OnLoad" // of type "T". // // iOS binaries (Flutter.framework/Flutter) should only export Objective-C // Symbols from the Flutter namespace. These are either of type // "(__DATA,__common)" or "(__DATA,__objc_data)". /// Takes the path to the out directory as the first argument, and the path to /// the buildtools directory as the second argument. /// /// If the second argument is not specified, for backwards compatibility, it is /// assumed that it is ../buildtools relative to the first parameter (the out /// directory). void main(List<String> arguments) { if (arguments.isEmpty || arguments.length > 2) { print('usage: dart verify_exported.dart OUT_DIR [BUILDTOOLS]'); exit(1); } String outPath = arguments.first; if (p.isRelative(outPath)) { /// If path is relative then create a full path starting from the engine checkout /// repository. if (!Platform.environment.containsKey('ENGINE_CHECKOUT_PATH')) { print('ENGINE_CHECKOUT_PATH env variable is mandatory when using relative destination path'); exit(1); } final String engineCheckoutPath = Platform.environment['ENGINE_CHECKOUT_PATH']!; outPath = p.join(engineCheckoutPath, outPath); } final String buildToolsPath = arguments.length == 1 ? p.join(p.dirname(outPath), 'buildtools') : arguments[1]; String platform; if (Platform.isLinux) { platform = 'linux-x64'; } else if (Platform.isMacOS) { platform = 'mac-x64'; } else { throw UnimplementedError('Script only support running on Linux or MacOS.'); } final String nmPath = p.join(buildToolsPath, platform, 'clang', 'bin', 'llvm-nm'); if (!Directory(outPath).existsSync()) { print('error: build out directory not found: $outPath'); exit(1); } final Iterable<String> releaseBuilds = Directory(outPath).listSync() .whereType<Directory>() .map<String>((FileSystemEntity dir) => p.basename(dir.path)) .where((String s) => s.contains('_release')); final Iterable<String> iosReleaseBuilds = releaseBuilds .where((String s) => s.startsWith('ios_')); final Iterable<String> androidReleaseBuilds = releaseBuilds .where((String s) => s.startsWith('android_')); final Iterable<String> hostReleaseBuilds = releaseBuilds .where((String s) => s.startsWith('host_')); int failures = 0; failures += _checkIos(outPath, nmPath, iosReleaseBuilds); failures += _checkAndroid(outPath, nmPath, androidReleaseBuilds); if (Platform.isLinux) { failures += _checkLinux(outPath, nmPath, hostReleaseBuilds); } print('Failing checks: $failures'); exit(failures); } int _checkIos(String outPath, String nmPath, Iterable<String> builds) { int failures = 0; for (final String build in builds) { final String libFlutter = p.join(outPath, build, 'Flutter.framework', 'Flutter'); if (!File(libFlutter).existsSync()) { print('SKIPPING: $libFlutter does not exist.'); continue; } final ProcessResult nmResult = Process.runSync(nmPath, <String>['-gUm', libFlutter]); if (nmResult.exitCode != 0) { print('ERROR: failed to execute "nm -gUm $libFlutter":\n${nmResult.stderr}'); failures++; continue; } final Iterable<NmEntry> unexpectedEntries = NmEntry.parse(nmResult.stdout as String).where((NmEntry entry) { final bool cSymbol = (entry.type == '(__DATA,__common)' || entry.type == '(__DATA,__const)') && entry.name.startsWith('_Flutter'); final bool cInternalSymbol = entry.type == '(__TEXT,__text)' && entry.name.startsWith('_InternalFlutter'); final bool objcSymbol = entry.type == '(__DATA,__objc_data)' && (entry.name.startsWith(r'_OBJC_METACLASS_$_Flutter') || entry.name.startsWith(r'_OBJC_CLASS_$_Flutter')); return !(cSymbol || cInternalSymbol || objcSymbol); }); if (unexpectedEntries.isNotEmpty) { print('ERROR: $libFlutter exports unexpected symbols:'); print(unexpectedEntries.fold<String>('', (String previous, NmEntry entry) { return '${previous == '' ? '' : '$previous\n'} ${entry.type} ${entry.name}'; })); failures++; } else { print('OK: $libFlutter'); } } return failures; } int _checkAndroid(String outPath, String nmPath, Iterable<String> builds) { int failures = 0; for (final String build in builds) { final String libFlutter = p.join(outPath, build, 'libflutter.so'); if (!File(libFlutter).existsSync()) { print('SKIPPING: $libFlutter does not exist.'); continue; } final ProcessResult nmResult = Process.runSync(nmPath, <String>['-gU', libFlutter]); if (nmResult.exitCode != 0) { print('ERROR: failed to execute "nm -gU $libFlutter":\n${nmResult.stderr}'); failures++; continue; } final Iterable<NmEntry> entries = NmEntry.parse(nmResult.stdout as String); final Map<String, String> entryMap = <String, String>{ for (final NmEntry entry in entries) entry.name: entry.type, }; final Map<String, String> expectedSymbols = <String, String>{ 'JNI_OnLoad': 'T', '_binary_icudtl_dat_size': 'R', '_binary_icudtl_dat_start': 'R', }; final Map<String, String> badSymbols = <String, String>{}; for (final String key in entryMap.keys) { if (entryMap[key] != expectedSymbols[key]) { badSymbols[key] = entryMap[key]!; } } if (badSymbols.isNotEmpty) { print('ERROR: $libFlutter exports the wrong symbols'); print(' Expected $expectedSymbols'); print(' Library has $entryMap.'); failures++; } else { print('OK: $libFlutter'); } } return failures; } int _checkLinux(String outPath, String nmPath, Iterable<String> builds) { int failures = 0; for (final String build in builds) { final String libFlutter = p.join(outPath, build, 'libflutter_engine.so'); if (!File(libFlutter).existsSync()) { print('SKIPPING: $libFlutter does not exist.'); continue; } final ProcessResult nmResult = Process.runSync(nmPath, <String>['-gUD', libFlutter]); if (nmResult.exitCode != 0) { print('ERROR: failed to execute "nm -gUD $libFlutter":\n${nmResult.stderr}'); failures++; continue; } final List<NmEntry> entries = NmEntry.parse(nmResult.stdout as String).toList(); for (final NmEntry entry in entries) { if (entry.type != 'T' && entry.type != 'R') { print('ERROR: $libFlutter exports an unexpected symbol type: ($entry)'); print(' Library has $entries.'); failures++; break; } if (!(entry.name.startsWith('Flutter') || entry.name.startsWith('__Flutter') || entry.name.startsWith('kFlutter') || entry.name.startsWith('InternalFlutter') || entry.name.startsWith('kInternalFlutter'))) { print('ERROR: $libFlutter exports an unexpected symbol name: ($entry)'); print(' Library has $entries.'); failures++; break; } } } return failures; } class NmEntry { NmEntry._(this.type, this.name); final String type; final String name; static Iterable<NmEntry> parse(String stdout) { return LineSplitter.split(stdout).map((String line) { final List<String> parts = line.split(' '); return NmEntry._(parts[1], parts.last); }); } @override String toString() => '$name: $type'; }
engine/testing/symbols/verify_exported.dart/0
{ "file_path": "engine/testing/symbols/verify_exported.dart", "repo_id": "engine", "token_count": 2915 }
388
// 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 <cassert> #include <memory> #include <optional> #include "flutter/flutter_vma/flutter_skia_vma.h" #include "flutter/fml/logging.h" #include "flutter/shell/common/context_options.h" #include "flutter/testing/test_vulkan_context.h" #include "flutter/vulkan/vulkan_skia_proc_table.h" #include "flutter/fml/memory/ref_ptr.h" #include "flutter/fml/native_library.h" #include "flutter/vulkan/swiftshader_path.h" #include "third_party/skia/include/core/SkSurface.h" #include "third_party/skia/include/gpu/GrDirectContext.h" #include "third_party/skia/include/gpu/ganesh/vk/GrVkDirectContext.h" #include "third_party/skia/include/gpu/vk/GrVkExtensions.h" #include "vulkan/vulkan_core.h" namespace flutter { namespace testing { TestVulkanContext::TestVulkanContext() { // --------------------------------------------------------------------------- // Initialize basic Vulkan state using the Swiftshader ICD. // --------------------------------------------------------------------------- const char* vulkan_icd = VULKAN_SO_PATH; // TODO(96949): Clean this up and pass a native library directly to // VulkanProcTable. if (!fml::NativeLibrary::Create(VULKAN_SO_PATH)) { FML_LOG(ERROR) << "Couldn't find Vulkan ICD \"" << vulkan_icd << "\", trying \"libvulkan.so\" instead."; vulkan_icd = "libvulkan.so"; } FML_LOG(INFO) << "Using Vulkan ICD: " << vulkan_icd; vk_ = fml::MakeRefCounted<vulkan::VulkanProcTable>(vulkan_icd); if (!vk_ || !vk_->HasAcquiredMandatoryProcAddresses()) { FML_LOG(ERROR) << "Proc table has not acquired mandatory proc addresses."; return; } application_ = std::make_unique<vulkan::VulkanApplication>( *vk_, "Flutter Unittests", std::vector<std::string>{}, VK_MAKE_VERSION(1, 0, 0), VK_MAKE_VERSION(1, 0, 0), true); if (!application_->IsValid()) { FML_LOG(ERROR) << "Failed to initialize basic Vulkan state."; return; } if (!vk_->AreInstanceProcsSetup()) { FML_LOG(ERROR) << "Failed to acquire full proc table."; return; } device_ = application_->AcquireFirstCompatibleLogicalDevice(); if (!device_ || !device_->IsValid()) { FML_LOG(ERROR) << "Failed to create compatible logical device."; return; } // --------------------------------------------------------------------------- // Create a Skia context. // For creating SkSurfaces from VkImages and snapshotting them, etc. // --------------------------------------------------------------------------- uint32_t skia_features = 0; if (!device_->GetPhysicalDeviceFeaturesSkia(&skia_features)) { FML_LOG(ERROR) << "Failed to get physical device features."; return; } auto get_proc = vulkan::CreateSkiaGetProc(vk_); if (get_proc == nullptr) { FML_LOG(ERROR) << "Failed to create Vulkan getProc for Skia."; return; } sk_sp<skgpu::VulkanMemoryAllocator> allocator = flutter::FlutterSkiaVulkanMemoryAllocator::Make( VK_MAKE_VERSION(1, 0, 0), application_->GetInstance(), device_->GetPhysicalDeviceHandle(), device_->GetHandle(), vk_, true); GrVkExtensions extensions; GrVkBackendContext backend_context = {}; backend_context.fInstance = application_->GetInstance(); backend_context.fPhysicalDevice = device_->GetPhysicalDeviceHandle(); backend_context.fDevice = device_->GetHandle(); backend_context.fQueue = device_->GetQueueHandle(); backend_context.fGraphicsQueueIndex = device_->GetGraphicsQueueIndex(); backend_context.fMinAPIVersion = VK_MAKE_VERSION(1, 0, 0); backend_context.fMaxAPIVersion = VK_MAKE_VERSION(1, 0, 0); backend_context.fFeatures = skia_features; backend_context.fVkExtensions = &extensions; backend_context.fGetProc = get_proc; backend_context.fOwnsInstanceAndDevice = false; backend_context.fMemoryAllocator = allocator; GrContextOptions options = MakeDefaultContextOptions(ContextType::kRender, GrBackendApi::kVulkan); options.fReduceOpsTaskSplitting = GrContextOptions::Enable::kNo; context_ = GrDirectContexts::MakeVulkan(backend_context, options); } TestVulkanContext::~TestVulkanContext() { if (context_) { context_->releaseResourcesAndAbandonContext(); } } std::optional<TestVulkanImage> TestVulkanContext::CreateImage( const SkISize& size) const { TestVulkanImage result; VkImageCreateInfo info = { .sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = nullptr, .flags = 0, .imageType = VK_IMAGE_TYPE_2D, .format = VK_FORMAT_R8G8B8A8_UNORM, .extent = VkExtent3D{static_cast<uint32_t>(size.width()), static_cast<uint32_t>(size.height()), 1}, .mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL, .usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = nullptr, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED, }; VkImage image; if (VK_CALL_LOG_ERROR(VK_CALL_LOG_ERROR( vk_->CreateImage(device_->GetHandle(), &info, nullptr, &image)))) { return std::nullopt; } result.image_ = vulkan::VulkanHandle<VkImage>( image, [&vk = vk_, &device = device_](VkImage image) { vk->DestroyImage(device->GetHandle(), image, nullptr); }); VkMemoryRequirements mem_req; vk_->GetImageMemoryRequirements(device_->GetHandle(), image, &mem_req); VkMemoryAllocateInfo alloc_info{}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = mem_req.size; alloc_info.memoryTypeIndex = static_cast<uint32_t>(__builtin_ctz( mem_req.memoryTypeBits & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)); VkDeviceMemory memory; if (VK_CALL_LOG_ERROR(vk_->AllocateMemory(device_->GetHandle(), &alloc_info, nullptr, &memory)) != VK_SUCCESS) { return std::nullopt; } result.memory_ = vulkan::VulkanHandle<VkDeviceMemory>{ memory, [&vk = vk_, &device = device_](VkDeviceMemory memory) { vk->FreeMemory(device->GetHandle(), memory, nullptr); }}; if (VK_CALL_LOG_ERROR(VK_CALL_LOG_ERROR(vk_->BindImageMemory( device_->GetHandle(), result.image_, result.memory_, 0)))) { return std::nullopt; } result.context_ = fml::RefPtr<TestVulkanContext>(const_cast<TestVulkanContext*>(this)); return result; } sk_sp<GrDirectContext> TestVulkanContext::GetGrDirectContext() const { return context_; } } // namespace testing } // namespace flutter
engine/testing/test_vulkan_context.cc/0
{ "file_path": "engine/testing/test_vulkan_context.cc", "repo_id": "engine", "token_count": 2615 }
389
# `flutter/third_party` This directory contains third-party code that is a combination of: - Code that is vendored into the Flutter repository, from an external source. For example, we might have `third_party/glfw`, which contains the GLFW library, vendored from an external repository. > 💡 **TIP**: See [`DEPS`](../DEPS) for where these sources are declared. - Code that originates from another repository, but is copied (sometimes with alterations) into the Flutter repository. For an example, see [`third_party/spring_animation`](spring_animation/README.md). - Code that is licensed separately from the rest of the Flutter repository. For example, see [`third_party/txt`](txt/). When adding a new _externally_ sourced third-party library, update `.gitignore`: ```diff # Ignores all third_party/ directories except for the ones we want to track. + !{folder_name}/ ```
engine/third_party/README.md/0
{ "file_path": "engine/third_party/README.md", "repo_id": "engine", "token_count": 257 }
390
// 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_COORDINATE_SYSTEM_H_ #define UI_ACCESSIBILITY_AX_COORDINATE_SYSTEM_H_ namespace ui { // The coordinate system of bounds or points. The origin for all coordinate // systems is the upper left hand corner of the region. Frame coordinates // correspond to the current frame and root frame coordinates are relative to // the topmost accessibility tree of the same type. For web content, root frame // coordinates are relative to the root frame of the web page. From within an // accessibility tree whose root is an iframe, frame coordinates are relative to // the region of the iframe. From an iframe leaf accessibility node, frame // coordinates are relative to the containing accessibility tree. For native UI, // frame coordinates are relative to the current window whereas root frame // coordinates are relative to the top-level window. The frame coordinates are // equivalent to the root frame coordinates when the current accessibility tree // is the root accessibility tree. // kScreenPhysicalPixels: Relative to screen space in hardware pixels // kScreenDIPs: Relative to screen space in device-independent pixels // (i.e. accounting for display DPI) // kRootFrame: Relative to the top-level accessibility tree of // the same type // kFrame: Relative to the current accessibility tree enum class AXCoordinateSystem { kScreenPhysicalPixels, kScreenDIPs, kRootFrame, kFrame }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_COORDINATE_SYSTEM_H_
engine/third_party/accessibility/ax/ax_coordinate_system.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_coordinate_system.h", "repo_id": "engine", "token_count": 482 }
391
// Copyright 2013 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_node_data.h" #include <algorithm> #include <cstddef> #include <iterator> #include <set> #include <utility> #include "ax_enum_util.h" #include "ax_role_properties.h" #include "base/container_utils.h" #include "base/logging.h" #include "base/no_destructor.h" #include "base/string_utils.h" namespace ui { namespace { bool IsFlagSet(uint32_t bitfield, uint32_t flag) { return (bitfield & (1U << flag)) != 0; } bool IsFlagSet(uint64_t bitfield, uint32_t flag) { return (bitfield & (1ULL << flag)) != 0; } uint32_t ModifyFlag(uint32_t bitfield, uint32_t flag, bool set) { return set ? (bitfield |= (1U << flag)) : (bitfield &= ~(1U << flag)); } uint64_t ModifyFlag(uint64_t bitfield, uint32_t flag, bool set) { return set ? (bitfield |= (1ULL << flag)) : (bitfield &= ~(1ULL << flag)); } std::string StateBitfieldToString(uint32_t state_enum) { std::string str; for (uint32_t i = static_cast<uint32_t>(ax::mojom::State::kNone) + 1; i <= static_cast<uint32_t>(ax::mojom::State::kMaxValue); ++i) { if (IsFlagSet(state_enum, i)) str += " " + base::ToUpperASCII(ui::ToString(static_cast<ax::mojom::State>(i))); } return str; } std::string ActionsBitfieldToString(uint64_t actions) { std::string str; for (uint32_t i = static_cast<uint32_t>(ax::mojom::Action::kNone) + 1; i <= static_cast<uint32_t>(ax::mojom::Action::kMaxValue); ++i) { if (IsFlagSet(actions, i)) { str += ui::ToString(static_cast<ax::mojom::Action>(i)); actions = ModifyFlag(actions, i, false); str += actions ? "," : ""; } } return str; } std::string IntVectorToString(const std::vector<int>& items) { std::string str; for (size_t i = 0; i < items.size(); ++i) { if (i > 0) str += ","; str += base::NumberToString(items[i]); } return str; } // Predicate that returns true if the first value of a pair is |first|. template <typename FirstType, typename SecondType> struct FirstIs { explicit FirstIs(FirstType first) : first_(first) {} bool operator()(std::pair<FirstType, SecondType> const& p) { return p.first == first_; } FirstType first_; }; // Helper function that finds a key in a vector of pairs by matching on the // first value, and returns an iterator. template <typename FirstType, typename SecondType> typename std::vector<std::pair<FirstType, SecondType>>::const_iterator FindInVectorOfPairs( FirstType first, const std::vector<std::pair<FirstType, SecondType>>& vector) { return std::find_if(vector.begin(), vector.end(), FirstIs<FirstType, SecondType>(first)); } } // namespace // Return true if |attr| is a node ID that would need to be mapped when // renumbering the ids in a combined tree. bool IsNodeIdIntAttribute(ax::mojom::IntAttribute attr) { switch (attr) { case ax::mojom::IntAttribute::kActivedescendantId: case ax::mojom::IntAttribute::kErrormessageId: case ax::mojom::IntAttribute::kInPageLinkTargetId: case ax::mojom::IntAttribute::kMemberOfId: case ax::mojom::IntAttribute::kNextOnLineId: case ax::mojom::IntAttribute::kPopupForId: case ax::mojom::IntAttribute::kPreviousOnLineId: case ax::mojom::IntAttribute::kTableHeaderId: case ax::mojom::IntAttribute::kTableColumnHeaderId: case ax::mojom::IntAttribute::kTableRowHeaderId: case ax::mojom::IntAttribute::kNextFocusId: case ax::mojom::IntAttribute::kPreviousFocusId: return true; // Note: all of the attributes are included here explicitly, // rather than using "default:", so that it's a compiler error to // add a new attribute without explicitly considering whether it's // a node id attribute or not. case ax::mojom::IntAttribute::kNone: case ax::mojom::IntAttribute::kDefaultActionVerb: case ax::mojom::IntAttribute::kScrollX: case ax::mojom::IntAttribute::kScrollXMin: case ax::mojom::IntAttribute::kScrollXMax: case ax::mojom::IntAttribute::kScrollY: case ax::mojom::IntAttribute::kScrollYMin: case ax::mojom::IntAttribute::kScrollYMax: case ax::mojom::IntAttribute::kTextSelStart: case ax::mojom::IntAttribute::kTextSelEnd: case ax::mojom::IntAttribute::kTableRowCount: case ax::mojom::IntAttribute::kTableColumnCount: case ax::mojom::IntAttribute::kTableRowIndex: case ax::mojom::IntAttribute::kTableColumnIndex: case ax::mojom::IntAttribute::kTableCellColumnIndex: case ax::mojom::IntAttribute::kTableCellColumnSpan: case ax::mojom::IntAttribute::kTableCellRowIndex: case ax::mojom::IntAttribute::kTableCellRowSpan: case ax::mojom::IntAttribute::kSortDirection: case ax::mojom::IntAttribute::kHierarchicalLevel: case ax::mojom::IntAttribute::kNameFrom: case ax::mojom::IntAttribute::kDescriptionFrom: case ax::mojom::IntAttribute::kSetSize: case ax::mojom::IntAttribute::kPosInSet: case ax::mojom::IntAttribute::kColorValue: case ax::mojom::IntAttribute::kAriaCurrentState: case ax::mojom::IntAttribute::kHasPopup: case ax::mojom::IntAttribute::kBackgroundColor: case ax::mojom::IntAttribute::kColor: case ax::mojom::IntAttribute::kInvalidState: case ax::mojom::IntAttribute::kCheckedState: case ax::mojom::IntAttribute::kRestriction: case ax::mojom::IntAttribute::kListStyle: case ax::mojom::IntAttribute::kTextAlign: case ax::mojom::IntAttribute::kTextDirection: case ax::mojom::IntAttribute::kTextPosition: case ax::mojom::IntAttribute::kTextStyle: case ax::mojom::IntAttribute::kTextOverlineStyle: case ax::mojom::IntAttribute::kTextStrikethroughStyle: case ax::mojom::IntAttribute::kTextUnderlineStyle: case ax::mojom::IntAttribute::kAriaColumnCount: case ax::mojom::IntAttribute::kAriaCellColumnIndex: case ax::mojom::IntAttribute::kAriaCellColumnSpan: case ax::mojom::IntAttribute::kAriaRowCount: case ax::mojom::IntAttribute::kAriaCellRowIndex: case ax::mojom::IntAttribute::kAriaCellRowSpan: case ax::mojom::IntAttribute::kImageAnnotationStatus: case ax::mojom::IntAttribute::kDropeffect: case ax::mojom::IntAttribute::kDOMNodeId: return false; } BASE_UNREACHABLE(); return false; } // Return true if |attr| contains a vector of node ids that would need // to be mapped when renumbering the ids in a combined tree. bool IsNodeIdIntListAttribute(ax::mojom::IntListAttribute attr) { switch (attr) { case ax::mojom::IntListAttribute::kControlsIds: case ax::mojom::IntListAttribute::kDetailsIds: case ax::mojom::IntListAttribute::kDescribedbyIds: case ax::mojom::IntListAttribute::kFlowtoIds: case ax::mojom::IntListAttribute::kIndirectChildIds: case ax::mojom::IntListAttribute::kLabelledbyIds: case ax::mojom::IntListAttribute::kRadioGroupIds: return true; // Note: all of the attributes are included here explicitly, // rather than using "default:", so that it's a compiler error to // add a new attribute without explicitly considering whether it's // a node id attribute or not. case ax::mojom::IntListAttribute::kNone: case ax::mojom::IntListAttribute::kMarkerTypes: case ax::mojom::IntListAttribute::kMarkerStarts: case ax::mojom::IntListAttribute::kMarkerEnds: case ax::mojom::IntListAttribute::kCharacterOffsets: case ax::mojom::IntListAttribute::kCachedLineStarts: case ax::mojom::IntListAttribute::kWordStarts: case ax::mojom::IntListAttribute::kWordEnds: case ax::mojom::IntListAttribute::kCustomActionIds: return false; } BASE_UNREACHABLE(); return false; } AXNodeData::AXNodeData() : role(ax::mojom::Role::kUnknown), state(0U), actions(0ULL) {} AXNodeData::~AXNodeData() = default; AXNodeData::AXNodeData(const AXNodeData& other) { id = other.id; role = other.role; state = other.state; actions = other.actions; string_attributes = other.string_attributes; int_attributes = other.int_attributes; float_attributes = other.float_attributes; bool_attributes = other.bool_attributes; intlist_attributes = other.intlist_attributes; stringlist_attributes = other.stringlist_attributes; html_attributes = other.html_attributes; child_ids = other.child_ids; relative_bounds = other.relative_bounds; } AXNodeData::AXNodeData(AXNodeData&& other) { id = other.id; role = other.role; state = other.state; actions = other.actions; string_attributes.swap(other.string_attributes); int_attributes.swap(other.int_attributes); float_attributes.swap(other.float_attributes); bool_attributes.swap(other.bool_attributes); intlist_attributes.swap(other.intlist_attributes); stringlist_attributes.swap(other.stringlist_attributes); html_attributes.swap(other.html_attributes); child_ids.swap(other.child_ids); relative_bounds = other.relative_bounds; } AXNodeData& AXNodeData::operator=(AXNodeData other) { id = other.id; role = other.role; state = other.state; actions = other.actions; string_attributes = other.string_attributes; int_attributes = other.int_attributes; float_attributes = other.float_attributes; bool_attributes = other.bool_attributes; intlist_attributes = other.intlist_attributes; stringlist_attributes = other.stringlist_attributes; html_attributes = other.html_attributes; child_ids = other.child_ids; relative_bounds = other.relative_bounds; return *this; } bool AXNodeData::HasBoolAttribute(ax::mojom::BoolAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, bool_attributes); return iter != bool_attributes.end(); } bool AXNodeData::GetBoolAttribute(ax::mojom::BoolAttribute attribute) const { bool result; if (GetBoolAttribute(attribute, &result)) return result; return false; } bool AXNodeData::GetBoolAttribute(ax::mojom::BoolAttribute attribute, bool* value) const { auto iter = FindInVectorOfPairs(attribute, bool_attributes); if (iter != bool_attributes.end()) { *value = iter->second; return true; } return false; } bool AXNodeData::HasFloatAttribute(ax::mojom::FloatAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, float_attributes); return iter != float_attributes.end(); } float AXNodeData::GetFloatAttribute(ax::mojom::FloatAttribute attribute) const { float result; if (GetFloatAttribute(attribute, &result)) return result; return 0.0; } bool AXNodeData::GetFloatAttribute(ax::mojom::FloatAttribute attribute, float* value) const { auto iter = FindInVectorOfPairs(attribute, float_attributes); if (iter != float_attributes.end()) { *value = iter->second; return true; } return false; } bool AXNodeData::HasIntAttribute(ax::mojom::IntAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, int_attributes); return iter != int_attributes.end(); } int AXNodeData::GetIntAttribute(ax::mojom::IntAttribute attribute) const { int result; if (GetIntAttribute(attribute, &result)) return result; return 0; } bool AXNodeData::GetIntAttribute(ax::mojom::IntAttribute attribute, int* value) const { auto iter = FindInVectorOfPairs(attribute, int_attributes); if (iter != int_attributes.end()) { *value = static_cast<int>(iter->second); return true; } return false; } bool AXNodeData::HasStringAttribute( ax::mojom::StringAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, string_attributes); return iter != string_attributes.end(); } const std::string& AXNodeData::GetStringAttribute( ax::mojom::StringAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, string_attributes); return iter != string_attributes.end() ? iter->second : base::EmptyString(); } bool AXNodeData::GetStringAttribute(ax::mojom::StringAttribute attribute, std::string* value) const { auto iter = FindInVectorOfPairs(attribute, string_attributes); if (iter != string_attributes.end()) { *value = iter->second; return true; } return false; } std::u16string AXNodeData::GetString16Attribute( ax::mojom::StringAttribute attribute) const { std::string value_utf8; if (!GetStringAttribute(attribute, &value_utf8)) return std::u16string(); return base::UTF8ToUTF16(value_utf8); } bool AXNodeData::GetString16Attribute(ax::mojom::StringAttribute attribute, std::u16string* value) const { std::string value_utf8; if (!GetStringAttribute(attribute, &value_utf8)) return false; *value = base::UTF8ToUTF16(value_utf8); return true; } bool AXNodeData::HasIntListAttribute( ax::mojom::IntListAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, intlist_attributes); return iter != intlist_attributes.end(); } const std::vector<int32_t>& AXNodeData::GetIntListAttribute( ax::mojom::IntListAttribute attribute) const { static const base::NoDestructor<std::vector<int32_t>> empty_vector; auto iter = FindInVectorOfPairs(attribute, intlist_attributes); if (iter != intlist_attributes.end()) return iter->second; return *empty_vector; } bool AXNodeData::GetIntListAttribute(ax::mojom::IntListAttribute attribute, std::vector<int32_t>* value) const { auto iter = FindInVectorOfPairs(attribute, intlist_attributes); if (iter != intlist_attributes.end()) { *value = iter->second; return true; } return false; } bool AXNodeData::HasStringListAttribute( ax::mojom::StringListAttribute attribute) const { auto iter = FindInVectorOfPairs(attribute, stringlist_attributes); return iter != stringlist_attributes.end(); } const std::vector<std::string>& AXNodeData::GetStringListAttribute( ax::mojom::StringListAttribute attribute) const { static const base::NoDestructor<std::vector<std::string>> empty_vector; auto iter = FindInVectorOfPairs(attribute, stringlist_attributes); if (iter != stringlist_attributes.end()) return iter->second; return *empty_vector; } bool AXNodeData::GetStringListAttribute( ax::mojom::StringListAttribute attribute, std::vector<std::string>* value) const { auto iter = FindInVectorOfPairs(attribute, stringlist_attributes); if (iter != stringlist_attributes.end()) { *value = iter->second; return true; } return false; } bool AXNodeData::GetHtmlAttribute(const char* html_attr, std::string* value) const { for (const std::pair<std::string, std::string>& html_attribute : html_attributes) { const std::string& attr = html_attribute.first; if (base::LowerCaseEqualsASCII(attr, html_attr)) { *value = html_attribute.second; return true; } } return false; } bool AXNodeData::GetHtmlAttribute(const char* html_attr, std::u16string* value) const { std::string value_utf8; if (!GetHtmlAttribute(html_attr, &value_utf8)) return false; *value = base::UTF8ToUTF16(value_utf8); return true; } void AXNodeData::AddStringAttribute(ax::mojom::StringAttribute attribute, const std::string& value) { BASE_DCHECK(attribute != ax::mojom::StringAttribute::kNone); if (HasStringAttribute(attribute)) RemoveStringAttribute(attribute); string_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::AddIntAttribute(ax::mojom::IntAttribute attribute, int value) { BASE_DCHECK(attribute != ax::mojom::IntAttribute::kNone); if (HasIntAttribute(attribute)) RemoveIntAttribute(attribute); int_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::AddFloatAttribute(ax::mojom::FloatAttribute attribute, float value) { BASE_DCHECK(attribute != ax::mojom::FloatAttribute::kNone); if (HasFloatAttribute(attribute)) RemoveFloatAttribute(attribute); float_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::AddBoolAttribute(ax::mojom::BoolAttribute attribute, bool value) { BASE_DCHECK(attribute != ax::mojom::BoolAttribute::kNone); if (HasBoolAttribute(attribute)) RemoveBoolAttribute(attribute); bool_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::AddIntListAttribute(ax::mojom::IntListAttribute attribute, const std::vector<int32_t>& value) { BASE_DCHECK(attribute != ax::mojom::IntListAttribute::kNone); if (HasIntListAttribute(attribute)) RemoveIntListAttribute(attribute); intlist_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::AddStringListAttribute( ax::mojom::StringListAttribute attribute, const std::vector<std::string>& value) { BASE_DCHECK(attribute != ax::mojom::StringListAttribute::kNone); if (HasStringListAttribute(attribute)) RemoveStringListAttribute(attribute); stringlist_attributes.push_back(std::make_pair(attribute, value)); } void AXNodeData::RemoveStringAttribute(ax::mojom::StringAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::StringAttribute::kNone); base::EraseIf(string_attributes, [attribute](const auto& string_attribute) { return string_attribute.first == attribute; }); } void AXNodeData::RemoveIntAttribute(ax::mojom::IntAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::IntAttribute::kNone); base::EraseIf(int_attributes, [attribute](const auto& int_attribute) { return int_attribute.first == attribute; }); } void AXNodeData::RemoveFloatAttribute(ax::mojom::FloatAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::FloatAttribute::kNone); base::EraseIf(float_attributes, [attribute](const auto& float_attribute) { return float_attribute.first == attribute; }); } void AXNodeData::RemoveBoolAttribute(ax::mojom::BoolAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::BoolAttribute::kNone); base::EraseIf(bool_attributes, [attribute](const auto& bool_attribute) { return bool_attribute.first == attribute; }); } void AXNodeData::RemoveIntListAttribute(ax::mojom::IntListAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::IntListAttribute::kNone); base::EraseIf(intlist_attributes, [attribute](const auto& intlist_attribute) { return intlist_attribute.first == attribute; }); } void AXNodeData::RemoveStringListAttribute( ax::mojom::StringListAttribute attribute) { BASE_DCHECK(attribute != ax::mojom::StringListAttribute::kNone); base::EraseIf(stringlist_attributes, [attribute](const auto& stringlist_attribute) { return stringlist_attribute.first == attribute; }); } AXNodeTextStyles AXNodeData::GetTextStyles() const { AXNodeTextStyles style_attributes; GetIntAttribute(ax::mojom::IntAttribute::kBackgroundColor, &style_attributes.background_color); GetIntAttribute(ax::mojom::IntAttribute::kColor, &style_attributes.color); GetIntAttribute(ax::mojom::IntAttribute::kInvalidState, &style_attributes.invalid_state); GetIntAttribute(ax::mojom::IntAttribute::kTextOverlineStyle, &style_attributes.overline_style); GetIntAttribute(ax::mojom::IntAttribute::kTextDirection, &style_attributes.text_direction); GetIntAttribute(ax::mojom::IntAttribute::kTextPosition, &style_attributes.text_position); GetIntAttribute(ax::mojom::IntAttribute::kTextStrikethroughStyle, &style_attributes.strikethrough_style); GetIntAttribute(ax::mojom::IntAttribute::kTextStyle, &style_attributes.text_style); GetIntAttribute(ax::mojom::IntAttribute::kTextUnderlineStyle, &style_attributes.underline_style); GetFloatAttribute(ax::mojom::FloatAttribute::kFontSize, &style_attributes.font_size); GetFloatAttribute(ax::mojom::FloatAttribute::kFontWeight, &style_attributes.font_weight); GetStringAttribute(ax::mojom::StringAttribute::kFontFamily, &style_attributes.font_family); return style_attributes; } void AXNodeData::SetName(const std::string& name) { if (role == ax::mojom::Role::kNone) { BASE_LOG() << "A valid role is required before setting the name attribute, " "because " "the role is used for setting the required NameFrom attribute."; BASE_UNREACHABLE(); } auto iter = std::find_if(string_attributes.begin(), string_attributes.end(), [](const auto& string_attribute) { return string_attribute.first == ax::mojom::StringAttribute::kName; }); if (iter == string_attributes.end()) { string_attributes.push_back( std::make_pair(ax::mojom::StringAttribute::kName, name)); } else { iter->second = name; } if (HasIntAttribute(ax::mojom::IntAttribute::kNameFrom)) return; // Since this method is mostly used by tests which don't always set the // "NameFrom" attribute, we need to set it here to the most likely value if // not set, otherwise code that tries to calculate the node's inner text, its // hypertext, or even its value, might not know whether to include the name in // the result or not. // // For example, if there is a text field, but it is empty, i.e. it has no // value, its value could be its name if "NameFrom" is set to "kPlaceholder" // or to "kContents" but not if it's set to "kAttribute". Similarly, if there // is a button without any unignored children, it's name can only be // equivalent to its inner text if "NameFrom" is set to "kContents" or to // "kValue", but not if it is set to "kAttribute". if (IsText(role)) { SetNameFrom(ax::mojom::NameFrom::kContents); } else { SetNameFrom(ax::mojom::NameFrom::kAttribute); } } void AXNodeData::SetName(const std::u16string& name) { SetName(base::UTF16ToUTF8(name)); } void AXNodeData::SetNameExplicitlyEmpty() { SetNameFrom(ax::mojom::NameFrom::kAttributeExplicitlyEmpty); } void AXNodeData::SetDescription(const std::string& description) { AddStringAttribute(ax::mojom::StringAttribute::kDescription, description); } void AXNodeData::SetDescription(const std::u16string& description) { SetDescription(base::UTF16ToUTF8(description)); } void AXNodeData::SetValue(const std::string& value) { AddStringAttribute(ax::mojom::StringAttribute::kValue, value); } void AXNodeData::SetValue(const std::u16string& value) { SetValue(base::UTF16ToUTF8(value)); } void AXNodeData::SetTooltip(const std::string& value) { AddStringAttribute(ax::mojom::StringAttribute::kTooltip, value); } void AXNodeData::SetTooltip(const std::u16string& value) { SetTooltip(base::UTF16ToUTF8(value)); } bool AXNodeData::HasState(ax::mojom::State state_enum) const { return IsFlagSet(state, static_cast<uint32_t>(state_enum)); } bool AXNodeData::HasAction(ax::mojom::Action action) const { return IsFlagSet(actions, static_cast<uint32_t>(action)); } bool AXNodeData::HasTextStyle(ax::mojom::TextStyle text_style_enum) const { int32_t style = GetIntAttribute(ax::mojom::IntAttribute::kTextStyle); return IsFlagSet(static_cast<uint32_t>(style), static_cast<uint32_t>(text_style_enum)); } bool AXNodeData::HasDropeffect(ax::mojom::Dropeffect dropeffect_enum) const { int32_t dropeffect = GetIntAttribute(ax::mojom::IntAttribute::kDropeffect); return IsFlagSet(static_cast<uint32_t>(dropeffect), static_cast<uint32_t>(dropeffect_enum)); } void AXNodeData::AddState(ax::mojom::State state_enum) { BASE_DCHECK(static_cast<int>(state_enum) > static_cast<int>(ax::mojom::State::kNone)); BASE_DCHECK(static_cast<int>(state_enum) <= static_cast<int>(ax::mojom::State::kMaxValue)); state = ModifyFlag(state, static_cast<uint32_t>(state_enum), true); } void AXNodeData::RemoveState(ax::mojom::State state_enum) { BASE_DCHECK(static_cast<int>(state_enum) > static_cast<int>(ax::mojom::State::kNone)); BASE_DCHECK(static_cast<int>(state_enum) <= static_cast<int>(ax::mojom::State::kMaxValue)); state = ModifyFlag(state, static_cast<uint32_t>(state_enum), false); } void AXNodeData::AddAction(ax::mojom::Action action_enum) { switch (action_enum) { case ax::mojom::Action::kNone: BASE_UNREACHABLE(); break; // Note: all of the attributes are included here explicitly, rather than // using "default:", so that it's a compiler error to add a new action // without explicitly considering whether there are mutually exclusive // actions that can be performed on a UI control at the same time. case ax::mojom::Action::kBlur: case ax::mojom::Action::kFocus: { ax::mojom::Action excluded_action = (action_enum == ax::mojom::Action::kBlur) ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur; BASE_DCHECK(!HasAction(excluded_action)); break; } case ax::mojom::Action::kClearAccessibilityFocus: case ax::mojom::Action::kCollapse: case ax::mojom::Action::kCustomAction: case ax::mojom::Action::kDecrement: case ax::mojom::Action::kDoDefault: case ax::mojom::Action::kExpand: case ax::mojom::Action::kGetImageData: case ax::mojom::Action::kHitTest: case ax::mojom::Action::kIncrement: case ax::mojom::Action::kInternalInvalidateTree: case ax::mojom::Action::kLoadInlineTextBoxes: case ax::mojom::Action::kReplaceSelectedText: case ax::mojom::Action::kScrollToMakeVisible: case ax::mojom::Action::kScrollToPoint: case ax::mojom::Action::kSetAccessibilityFocus: case ax::mojom::Action::kSetScrollOffset: case ax::mojom::Action::kSetSelection: case ax::mojom::Action::kSetSequentialFocusNavigationStartingPoint: case ax::mojom::Action::kSetValue: case ax::mojom::Action::kShowContextMenu: case ax::mojom::Action::kScrollBackward: case ax::mojom::Action::kScrollForward: case ax::mojom::Action::kScrollUp: case ax::mojom::Action::kScrollDown: case ax::mojom::Action::kScrollLeft: case ax::mojom::Action::kScrollRight: case ax::mojom::Action::kGetTextLocation: case ax::mojom::Action::kAnnotatePageImages: case ax::mojom::Action::kSignalEndOfTest: case ax::mojom::Action::kHideTooltip: case ax::mojom::Action::kShowTooltip: break; } actions = ModifyFlag(actions, static_cast<uint32_t>(action_enum), true); } void AXNodeData::AddTextStyle(ax::mojom::TextStyle text_style_enum) { BASE_DCHECK(static_cast<int>(text_style_enum) >= static_cast<int>(ax::mojom::TextStyle::kMinValue)); BASE_DCHECK(static_cast<int>(text_style_enum) <= static_cast<int>(ax::mojom::TextStyle::kMaxValue)); int32_t style = GetIntAttribute(ax::mojom::IntAttribute::kTextStyle); style = ModifyFlag(static_cast<uint32_t>(style), static_cast<uint32_t>(text_style_enum), true); RemoveIntAttribute(ax::mojom::IntAttribute::kTextStyle); AddIntAttribute(ax::mojom::IntAttribute::kTextStyle, style); } void AXNodeData::AddDropeffect(ax::mojom::Dropeffect dropeffect_enum) { BASE_DCHECK(static_cast<int>(dropeffect_enum) >= static_cast<int>(ax::mojom::Dropeffect::kMinValue)); BASE_DCHECK(static_cast<int>(dropeffect_enum) <= static_cast<int>(ax::mojom::Dropeffect::kMaxValue)); int32_t dropeffect = GetIntAttribute(ax::mojom::IntAttribute::kDropeffect); dropeffect = ModifyFlag(static_cast<uint32_t>(dropeffect), static_cast<uint32_t>(dropeffect_enum), true); RemoveIntAttribute(ax::mojom::IntAttribute::kDropeffect); AddIntAttribute(ax::mojom::IntAttribute::kDropeffect, dropeffect); } ax::mojom::CheckedState AXNodeData::GetCheckedState() const { return static_cast<ax::mojom::CheckedState>( GetIntAttribute(ax::mojom::IntAttribute::kCheckedState)); } void AXNodeData::SetCheckedState(ax::mojom::CheckedState checked_state) { if (HasCheckedState()) RemoveIntAttribute(ax::mojom::IntAttribute::kCheckedState); if (checked_state != ax::mojom::CheckedState::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kCheckedState, static_cast<int32_t>(checked_state)); } } bool AXNodeData::HasCheckedState() const { return HasIntAttribute(ax::mojom::IntAttribute::kCheckedState); } ax::mojom::DefaultActionVerb AXNodeData::GetDefaultActionVerb() const { return static_cast<ax::mojom::DefaultActionVerb>( GetIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb)); } void AXNodeData::SetDefaultActionVerb( ax::mojom::DefaultActionVerb default_action_verb) { if (HasIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb)) RemoveIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb); if (default_action_verb != ax::mojom::DefaultActionVerb::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb, static_cast<int32_t>(default_action_verb)); } } ax::mojom::HasPopup AXNodeData::GetHasPopup() const { return static_cast<ax::mojom::HasPopup>( GetIntAttribute(ax::mojom::IntAttribute::kHasPopup)); } void AXNodeData::SetHasPopup(ax::mojom::HasPopup has_popup) { if (HasIntAttribute(ax::mojom::IntAttribute::kHasPopup)) RemoveIntAttribute(ax::mojom::IntAttribute::kHasPopup); if (has_popup != ax::mojom::HasPopup::kFalse) { AddIntAttribute(ax::mojom::IntAttribute::kHasPopup, static_cast<int32_t>(has_popup)); } } ax::mojom::InvalidState AXNodeData::GetInvalidState() const { return static_cast<ax::mojom::InvalidState>( GetIntAttribute(ax::mojom::IntAttribute::kInvalidState)); } void AXNodeData::SetInvalidState(ax::mojom::InvalidState invalid_state) { if (HasIntAttribute(ax::mojom::IntAttribute::kInvalidState)) RemoveIntAttribute(ax::mojom::IntAttribute::kInvalidState); if (invalid_state != ax::mojom::InvalidState::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kInvalidState, static_cast<int32_t>(invalid_state)); } } ax::mojom::NameFrom AXNodeData::GetNameFrom() const { return static_cast<ax::mojom::NameFrom>( GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)); } void AXNodeData::SetNameFrom(ax::mojom::NameFrom name_from) { if (HasIntAttribute(ax::mojom::IntAttribute::kNameFrom)) RemoveIntAttribute(ax::mojom::IntAttribute::kNameFrom); if (name_from != ax::mojom::NameFrom::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kNameFrom, static_cast<int32_t>(name_from)); } } ax::mojom::DescriptionFrom AXNodeData::GetDescriptionFrom() const { return static_cast<ax::mojom::DescriptionFrom>( GetIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom)); } void AXNodeData::SetDescriptionFrom( ax::mojom::DescriptionFrom description_from) { if (HasIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom)) RemoveIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom); if (description_from != ax::mojom::DescriptionFrom::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kDescriptionFrom, static_cast<int32_t>(description_from)); } } ax::mojom::TextPosition AXNodeData::GetTextPosition() const { return static_cast<ax::mojom::TextPosition>( GetIntAttribute(ax::mojom::IntAttribute::kTextPosition)); } void AXNodeData::SetTextPosition(ax::mojom::TextPosition text_position) { if (HasIntAttribute(ax::mojom::IntAttribute::kTextPosition)) RemoveIntAttribute(ax::mojom::IntAttribute::kTextPosition); if (text_position != ax::mojom::TextPosition::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kTextPosition, static_cast<int32_t>(text_position)); } } ax::mojom::ImageAnnotationStatus AXNodeData::GetImageAnnotationStatus() const { return static_cast<ax::mojom::ImageAnnotationStatus>( GetIntAttribute(ax::mojom::IntAttribute::kImageAnnotationStatus)); } void AXNodeData::SetImageAnnotationStatus( ax::mojom::ImageAnnotationStatus status) { if (HasIntAttribute(ax::mojom::IntAttribute::kImageAnnotationStatus)) RemoveIntAttribute(ax::mojom::IntAttribute::kImageAnnotationStatus); if (status != ax::mojom::ImageAnnotationStatus::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kImageAnnotationStatus, static_cast<int32_t>(status)); } } ax::mojom::Restriction AXNodeData::GetRestriction() const { return static_cast<ax::mojom::Restriction>( GetIntAttribute(ax::mojom::IntAttribute::kRestriction)); } void AXNodeData::SetRestriction(ax::mojom::Restriction restriction) { if (HasIntAttribute(ax::mojom::IntAttribute::kRestriction)) RemoveIntAttribute(ax::mojom::IntAttribute::kRestriction); if (restriction != ax::mojom::Restriction::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kRestriction, static_cast<int32_t>(restriction)); } } ax::mojom::ListStyle AXNodeData::GetListStyle() const { return static_cast<ax::mojom::ListStyle>( GetIntAttribute(ax::mojom::IntAttribute::kListStyle)); } void AXNodeData::SetListStyle(ax::mojom::ListStyle list_style) { if (HasIntAttribute(ax::mojom::IntAttribute::kListStyle)) RemoveIntAttribute(ax::mojom::IntAttribute::kListStyle); if (list_style != ax::mojom::ListStyle::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kListStyle, static_cast<int32_t>(list_style)); } } ax::mojom::TextAlign AXNodeData::GetTextAlign() const { return static_cast<ax::mojom::TextAlign>( GetIntAttribute(ax::mojom::IntAttribute::kTextAlign)); } void AXNodeData::SetTextAlign(ax::mojom::TextAlign text_align) { if (HasIntAttribute(ax::mojom::IntAttribute::kTextAlign)) RemoveIntAttribute(ax::mojom::IntAttribute::kTextAlign); AddIntAttribute(ax::mojom::IntAttribute::kTextAlign, static_cast<int32_t>(text_align)); } ax::mojom::WritingDirection AXNodeData::GetTextDirection() const { return static_cast<ax::mojom::WritingDirection>( GetIntAttribute(ax::mojom::IntAttribute::kTextDirection)); } void AXNodeData::SetTextDirection(ax::mojom::WritingDirection text_direction) { if (HasIntAttribute(ax::mojom::IntAttribute::kTextDirection)) RemoveIntAttribute(ax::mojom::IntAttribute::kTextDirection); if (text_direction != ax::mojom::WritingDirection::kNone) { AddIntAttribute(ax::mojom::IntAttribute::kTextDirection, static_cast<int32_t>(text_direction)); } } bool AXNodeData::IsActivatable() const { return IsTextField() || role == ax::mojom::Role::kListBox; } bool AXNodeData::IsButtonPressed() const { // Currently there is no internal representation for |aria-pressed|, and // we map |aria-pressed="true"| to ax::mojom::CheckedState::kTrue for a native // button or role="button". // https://www.w3.org/TR/wai-aria-1.1/#aria-pressed if (IsButton(role) && GetCheckedState() == ax::mojom::CheckedState::kTrue) return true; return false; } bool AXNodeData::IsClickable() const { // If it has a custom default action verb except for // ax::mojom::DefaultActionVerb::kClickAncestor, it's definitely clickable. // ax::mojom::DefaultActionVerb::kClickAncestor is used when an element with a // click listener is present in its ancestry chain. if (HasIntAttribute(ax::mojom::IntAttribute::kDefaultActionVerb) && (GetDefaultActionVerb() != ax::mojom::DefaultActionVerb::kClickAncestor)) return true; return ui::IsClickable(role); } bool AXNodeData::IsSelectable() const { // It's selectable if it has the attribute, whether it's true or false. return HasBoolAttribute(ax::mojom::BoolAttribute::kSelected) && GetRestriction() != ax::mojom::Restriction::kDisabled; } bool AXNodeData::IsIgnored() const { return HasState(ax::mojom::State::kIgnored) || role == ax::mojom::Role::kIgnored; } bool AXNodeData::IsInvisible() const { return HasState(ax::mojom::State::kInvisible); } bool AXNodeData::IsInvisibleOrIgnored() const { return IsIgnored() || IsInvisible(); } bool AXNodeData::IsInvocable() const { // A control is "invocable" if it initiates an action when activated but // does not maintain any state. A control that maintains state when activated // would be considered a toggle or expand-collapse element - these elements // are "clickable" but not "invocable". Similarly, if the action only involves // activating the control, such as when clicking a text field, the control is // not considered "invocable". return IsClickable() && !IsActivatable() && !SupportsExpandCollapse() && !SupportsToggle(role); } bool AXNodeData::IsMenuButton() const { // According to the WAI-ARIA spec, a menu button is a native button or an ARIA // role="button" that opens a menu. Although ARIA does not include a role // specifically for menu buttons, screen readers identify buttons that have // aria-haspopup="true" or aria-haspopup="menu" as menu buttons, and Blink // maps both to HasPopup::kMenu. // https://www.w3.org/TR/wai-aria-practices/#menubutton // https://www.w3.org/TR/wai-aria-1.1/#aria-haspopup if (IsButton(role) && GetHasPopup() == ax::mojom::HasPopup::kMenu) return true; return false; } bool AXNodeData::IsTextField() const { return IsPlainTextField() || IsRichTextField(); } bool AXNodeData::IsPasswordField() const { return IsTextField() && HasState(ax::mojom::State::kProtected); } bool AXNodeData::IsPlainTextField() const { // We need to check both the role and editable state, because some ARIA text // fields may in fact not be editable, whilst some editable fields might not // have the role. return !HasState(ax::mojom::State::kRichlyEditable) && (role == ax::mojom::Role::kTextField || role == ax::mojom::Role::kTextFieldWithComboBox || role == ax::mojom::Role::kSearchBox || GetBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot)); } bool AXNodeData::IsRichTextField() const { return GetBoolAttribute(ax::mojom::BoolAttribute::kEditableRoot) && HasState(ax::mojom::State::kRichlyEditable); } bool AXNodeData::IsReadOnlyOrDisabled() const { switch (GetRestriction()) { case ax::mojom::Restriction::kReadOnly: case ax::mojom::Restriction::kDisabled: return true; case ax::mojom::Restriction::kNone: { if (HasState(ax::mojom::State::kEditable) || HasState(ax::mojom::State::kRichlyEditable)) { return false; } // By default, when readonly is not supported, we assume the node is never // editable - then always readonly. return ShouldHaveReadonlyStateByDefault(role) || !IsReadOnlySupported(role); } } } bool AXNodeData::IsRangeValueSupported() const { if (role == ax::mojom::Role::kSplitter) { // According to the ARIA spec, role="separator" acts as a splitter only // when focusable, and supports a range only in that case. return HasState(ax::mojom::State::kFocusable); } return ui::IsRangeValueSupported(role); } bool AXNodeData::SupportsExpandCollapse() const { if (GetHasPopup() != ax::mojom::HasPopup::kFalse || HasState(ax::mojom::State::kExpanded) || HasState(ax::mojom::State::kCollapsed)) return true; return ui::SupportsExpandCollapse(role); } std::string AXNodeData::ToString() const { std::string result; result += "id=" + base::NumberToString(id); result += " "; result += ui::ToString(role); result += StateBitfieldToString(state); result += " " + relative_bounds.ToString(); for (const std::pair<ax::mojom::IntAttribute, int32_t>& int_attribute : int_attributes) { std::string value = base::NumberToString(int_attribute.second); switch (int_attribute.first) { case ax::mojom::IntAttribute::kDefaultActionVerb: result += std::string(" action=") + ui::ToString(static_cast<ax::mojom::DefaultActionVerb>( int_attribute.second)); break; case ax::mojom::IntAttribute::kScrollX: result += " scroll_x=" + value; break; case ax::mojom::IntAttribute::kScrollXMin: result += " scroll_x_min=" + value; break; case ax::mojom::IntAttribute::kScrollXMax: result += " scroll_x_max=" + value; break; case ax::mojom::IntAttribute::kScrollY: result += " scroll_y=" + value; break; case ax::mojom::IntAttribute::kScrollYMin: result += " scroll_y_min=" + value; break; case ax::mojom::IntAttribute::kScrollYMax: result += " scroll_y_max=" + value; break; case ax::mojom::IntAttribute::kHierarchicalLevel: result += " level=" + value; break; case ax::mojom::IntAttribute::kTextSelStart: result += " sel_start=" + value; break; case ax::mojom::IntAttribute::kTextSelEnd: result += " sel_end=" + value; break; case ax::mojom::IntAttribute::kAriaColumnCount: result += " aria_column_count=" + value; break; case ax::mojom::IntAttribute::kAriaCellColumnIndex: result += " aria_cell_column_index=" + value; break; case ax::mojom::IntAttribute::kAriaCellColumnSpan: result += " aria_cell_column_span=" + value; break; case ax::mojom::IntAttribute::kAriaRowCount: result += " aria_row_count=" + value; break; case ax::mojom::IntAttribute::kAriaCellRowIndex: result += " aria_cell_row_index=" + value; break; case ax::mojom::IntAttribute::kAriaCellRowSpan: result += " aria_cell_row_span=" + value; break; case ax::mojom::IntAttribute::kTableRowCount: result += " rows=" + value; break; case ax::mojom::IntAttribute::kTableColumnCount: result += " cols=" + value; break; case ax::mojom::IntAttribute::kTableCellColumnIndex: result += " col=" + value; break; case ax::mojom::IntAttribute::kTableCellRowIndex: result += " row=" + value; break; case ax::mojom::IntAttribute::kTableCellColumnSpan: result += " colspan=" + value; break; case ax::mojom::IntAttribute::kTableCellRowSpan: result += " rowspan=" + value; break; case ax::mojom::IntAttribute::kTableColumnHeaderId: result += " column_header_id=" + value; break; case ax::mojom::IntAttribute::kTableColumnIndex: result += " column_index=" + value; break; case ax::mojom::IntAttribute::kTableHeaderId: result += " header_id=" + value; break; case ax::mojom::IntAttribute::kTableRowHeaderId: result += " row_header_id=" + value; break; case ax::mojom::IntAttribute::kTableRowIndex: result += " row_index=" + value; break; case ax::mojom::IntAttribute::kSortDirection: switch (static_cast<ax::mojom::SortDirection>(int_attribute.second)) { case ax::mojom::SortDirection::kUnsorted: result += " sort_direction=none"; break; case ax::mojom::SortDirection::kAscending: result += " sort_direction=ascending"; break; case ax::mojom::SortDirection::kDescending: result += " sort_direction=descending"; break; case ax::mojom::SortDirection::kOther: result += " sort_direction=other"; break; default: break; } break; case ax::mojom::IntAttribute::kNameFrom: result += " name_from="; result += ui::ToString( static_cast<ax::mojom::NameFrom>(int_attribute.second)); break; case ax::mojom::IntAttribute::kDescriptionFrom: result += " description_from="; result += ui::ToString( static_cast<ax::mojom::DescriptionFrom>(int_attribute.second)); break; case ax::mojom::IntAttribute::kActivedescendantId: result += " activedescendant=" + value; break; case ax::mojom::IntAttribute::kErrormessageId: result += " errormessage=" + value; break; case ax::mojom::IntAttribute::kInPageLinkTargetId: result += " in_page_link_target_id=" + value; break; case ax::mojom::IntAttribute::kMemberOfId: result += " member_of_id=" + value; break; case ax::mojom::IntAttribute::kNextOnLineId: result += " next_on_line_id=" + value; break; case ax::mojom::IntAttribute::kPopupForId: result += " popup_for_id=" + value; break; case ax::mojom::IntAttribute::kPreviousOnLineId: result += " previous_on_line_id=" + value; break; case ax::mojom::IntAttribute::kColorValue: result += base::StringPrintf(" color_value=&%X", int_attribute.second); break; case ax::mojom::IntAttribute::kAriaCurrentState: switch ( static_cast<ax::mojom::AriaCurrentState>(int_attribute.second)) { case ax::mojom::AriaCurrentState::kFalse: result += " aria_current_state=false"; break; case ax::mojom::AriaCurrentState::kTrue: result += " aria_current_state=true"; break; case ax::mojom::AriaCurrentState::kPage: result += " aria_current_state=page"; break; case ax::mojom::AriaCurrentState::kStep: result += " aria_current_state=step"; break; case ax::mojom::AriaCurrentState::kLocation: result += " aria_current_state=location"; break; case ax::mojom::AriaCurrentState::kDate: result += " aria_current_state=date"; break; case ax::mojom::AriaCurrentState::kTime: result += " aria_current_state=time"; break; default: break; } break; case ax::mojom::IntAttribute::kBackgroundColor: result += base::StringPrintf(" background_color=&%X", int_attribute.second); break; case ax::mojom::IntAttribute::kColor: result += base::StringPrintf(" color=&%X", int_attribute.second); break; case ax::mojom::IntAttribute::kListStyle: switch (static_cast<ax::mojom::ListStyle>(int_attribute.second)) { case ax::mojom::ListStyle::kCircle: result += " list_style=circle"; break; case ax::mojom::ListStyle::kDisc: result += " list_style=disc"; break; case ax::mojom::ListStyle::kImage: result += " list_style=image"; break; case ax::mojom::ListStyle::kNumeric: result += " list_style=numeric"; break; case ax::mojom::ListStyle::kOther: result += " list_style=other"; break; case ax::mojom::ListStyle::kSquare: result += " list_style=square"; break; default: break; } break; case ax::mojom::IntAttribute::kTextAlign: result += " text_align="; result += ui::ToString( static_cast<ax::mojom::TextAlign>(int_attribute.second)); break; case ax::mojom::IntAttribute::kTextDirection: switch ( static_cast<ax::mojom::WritingDirection>(int_attribute.second)) { case ax::mojom::WritingDirection::kLtr: result += " text_direction=ltr"; break; case ax::mojom::WritingDirection::kRtl: result += " text_direction=rtl"; break; case ax::mojom::WritingDirection::kTtb: result += " text_direction=ttb"; break; case ax::mojom::WritingDirection::kBtt: result += " text_direction=btt"; break; default: break; } break; case ax::mojom::IntAttribute::kTextPosition: switch (static_cast<ax::mojom::TextPosition>(int_attribute.second)) { case ax::mojom::TextPosition::kNone: result += " text_position=none"; break; case ax::mojom::TextPosition::kSubscript: result += " text_position=subscript"; break; case ax::mojom::TextPosition::kSuperscript: result += " text_position=superscript"; break; default: break; } break; case ax::mojom::IntAttribute::kTextStyle: { std::string text_style_value; if (HasTextStyle(ax::mojom::TextStyle::kBold)) text_style_value += "bold,"; if (HasTextStyle(ax::mojom::TextStyle::kItalic)) text_style_value += "italic,"; if (HasTextStyle(ax::mojom::TextStyle::kUnderline)) text_style_value += "underline,"; if (HasTextStyle(ax::mojom::TextStyle::kLineThrough)) text_style_value += "line-through,"; if (HasTextStyle(ax::mojom::TextStyle::kOverline)) text_style_value += "overline,"; result += text_style_value.substr(0, text_style_value.size() - 1); break; } case ax::mojom::IntAttribute::kTextOverlineStyle: result += std::string(" text_overline_style=") + ui::ToString(static_cast<ax::mojom::TextDecorationStyle>( int_attribute.second)); break; case ax::mojom::IntAttribute::kTextStrikethroughStyle: result += std::string(" text_strikethrough_style=") + ui::ToString(static_cast<ax::mojom::TextDecorationStyle>( int_attribute.second)); break; case ax::mojom::IntAttribute::kTextUnderlineStyle: result += std::string(" text_underline_style=") + ui::ToString(static_cast<ax::mojom::TextDecorationStyle>( int_attribute.second)); break; case ax::mojom::IntAttribute::kSetSize: result += " setsize=" + value; break; case ax::mojom::IntAttribute::kPosInSet: result += " posinset=" + value; break; case ax::mojom::IntAttribute::kHasPopup: switch (static_cast<ax::mojom::HasPopup>(int_attribute.second)) { case ax::mojom::HasPopup::kTrue: result += " haspopup=true"; break; case ax::mojom::HasPopup::kMenu: result += " haspopup=menu"; break; case ax::mojom::HasPopup::kListbox: result += " haspopup=listbox"; break; case ax::mojom::HasPopup::kTree: result += " haspopup=tree"; break; case ax::mojom::HasPopup::kGrid: result += " haspopup=grid"; break; case ax::mojom::HasPopup::kDialog: result += " haspopup=dialog"; break; case ax::mojom::HasPopup::kFalse: default: break; } break; case ax::mojom::IntAttribute::kInvalidState: switch (static_cast<ax::mojom::InvalidState>(int_attribute.second)) { case ax::mojom::InvalidState::kFalse: result += " invalid_state=false"; break; case ax::mojom::InvalidState::kTrue: result += " invalid_state=true"; break; case ax::mojom::InvalidState::kOther: result += " invalid_state=other"; break; default: break; } break; case ax::mojom::IntAttribute::kCheckedState: switch (static_cast<ax::mojom::CheckedState>(int_attribute.second)) { case ax::mojom::CheckedState::kFalse: result += " checked_state=false"; break; case ax::mojom::CheckedState::kTrue: result += " checked_state=true"; break; case ax::mojom::CheckedState::kMixed: result += " checked_state=mixed"; break; default: break; } break; case ax::mojom::IntAttribute::kRestriction: switch (static_cast<ax::mojom::Restriction>(int_attribute.second)) { case ax::mojom::Restriction::kReadOnly: result += " restriction=readonly"; break; case ax::mojom::Restriction::kDisabled: result += " restriction=disabled"; break; default: break; } break; case ax::mojom::IntAttribute::kNextFocusId: result += " next_focus_id=" + value; break; case ax::mojom::IntAttribute::kPreviousFocusId: result += " previous_focus_id=" + value; break; case ax::mojom::IntAttribute::kImageAnnotationStatus: result += std::string(" image_annotation_status=") + ui::ToString(static_cast<ax::mojom::ImageAnnotationStatus>( int_attribute.second)); break; case ax::mojom::IntAttribute::kDropeffect: result += " dropeffect=" + value; break; case ax::mojom::IntAttribute::kDOMNodeId: result += " dom_node_id=" + value; break; case ax::mojom::IntAttribute::kNone: break; } } for (const std::pair<ax::mojom::StringAttribute, std::string>& string_attribute : string_attributes) { std::string value = string_attribute.second; switch (string_attribute.first) { case ax::mojom::StringAttribute::kAccessKey: result += " access_key=" + value; break; case ax::mojom::StringAttribute::kAriaInvalidValue: result += " aria_invalid_value=" + value; break; case ax::mojom::StringAttribute::kAutoComplete: result += " autocomplete=" + value; break; case ax::mojom::StringAttribute::kChildTreeId: result += " child_tree_id=" + value.substr(0, 8); break; case ax::mojom::StringAttribute::kClassName: result += " class_name=" + value; break; case ax::mojom::StringAttribute::kDescription: result += " description=" + value; break; case ax::mojom::StringAttribute::kDisplay: result += " display=" + value; break; case ax::mojom::StringAttribute::kFontFamily: result += " font-family=" + value; break; case ax::mojom::StringAttribute::kHtmlTag: result += " html_tag=" + value; break; case ax::mojom::StringAttribute::kImageAnnotation: result += " image_annotation=" + value; break; case ax::mojom::StringAttribute::kImageDataUrl: result += " image_data_url=(" + base::NumberToString(static_cast<int>(value.size())) + " bytes)"; break; case ax::mojom::StringAttribute::kInnerHtml: result += " inner_html=" + value; break; case ax::mojom::StringAttribute::kInputType: result += " input_type=" + value; break; case ax::mojom::StringAttribute::kKeyShortcuts: result += " key_shortcuts=" + value; break; case ax::mojom::StringAttribute::kLanguage: result += " language=" + value; break; case ax::mojom::StringAttribute::kLiveRelevant: result += " relevant=" + value; break; case ax::mojom::StringAttribute::kLiveStatus: result += " live=" + value; break; case ax::mojom::StringAttribute::kContainerLiveRelevant: result += " container_relevant=" + value; break; case ax::mojom::StringAttribute::kContainerLiveStatus: result += " container_live=" + value; break; case ax::mojom::StringAttribute::kPlaceholder: result += " placeholder=" + value; break; case ax::mojom::StringAttribute::kRole: result += " role=" + value; break; case ax::mojom::StringAttribute::kRoleDescription: result += " role_description=" + value; break; case ax::mojom::StringAttribute::kTooltip: result += " tooltip=" + value; break; case ax::mojom::StringAttribute::kUrl: result += " url=" + value; break; case ax::mojom::StringAttribute::kName: result += " name=" + value; break; case ax::mojom::StringAttribute::kValue: result += " value=" + value; break; case ax::mojom::StringAttribute::kNone: break; } } for (const std::pair<ax::mojom::FloatAttribute, float>& float_attribute : float_attributes) { std::string value = base::NumberToString(float_attribute.second); switch (float_attribute.first) { case ax::mojom::FloatAttribute::kValueForRange: result += " value_for_range=" + value; break; case ax::mojom::FloatAttribute::kMaxValueForRange: result += " max_value=" + value; break; case ax::mojom::FloatAttribute::kMinValueForRange: result += " min_value=" + value; break; case ax::mojom::FloatAttribute::kStepValueForRange: result += " step_value=" + value; break; case ax::mojom::FloatAttribute::kFontSize: result += " font_size=" + value; break; case ax::mojom::FloatAttribute::kFontWeight: result += " font_weight=" + value; break; case ax::mojom::FloatAttribute::kTextIndent: result += " text_indent=" + value; break; case ax::mojom::FloatAttribute::kNone: break; } } for (const std::pair<ax::mojom::BoolAttribute, bool>& bool_attribute : bool_attributes) { std::string value = bool_attribute.second ? "true" : "false"; switch (bool_attribute.first) { case ax::mojom::BoolAttribute::kEditableRoot: result += " editable_root=" + value; break; case ax::mojom::BoolAttribute::kLiveAtomic: result += " atomic=" + value; break; case ax::mojom::BoolAttribute::kBusy: result += " busy=" + value; break; case ax::mojom::BoolAttribute::kContainerLiveAtomic: result += " container_atomic=" + value; break; case ax::mojom::BoolAttribute::kContainerLiveBusy: result += " container_busy=" + value; break; case ax::mojom::BoolAttribute::kUpdateLocationOnly: result += " update_location_only=" + value; break; case ax::mojom::BoolAttribute::kCanvasHasFallback: result += " has_fallback=" + value; break; case ax::mojom::BoolAttribute::kModal: result += " modal=" + value; break; case ax::mojom::BoolAttribute::kScrollable: result += " scrollable=" + value; break; case ax::mojom::BoolAttribute::kClickable: result += " clickable=" + value; break; case ax::mojom::BoolAttribute::kClipsChildren: result += " clips_children=" + value; break; case ax::mojom::BoolAttribute::kNotUserSelectableStyle: result += " not_user_selectable=" + value; break; case ax::mojom::BoolAttribute::kSelected: result += " selected=" + value; break; case ax::mojom::BoolAttribute::kSelectedFromFocus: result += " selected_from_focus=" + value; break; case ax::mojom::BoolAttribute::kSupportsTextLocation: result += " supports_text_location=" + value; break; case ax::mojom::BoolAttribute::kGrabbed: result += " grabbed=" + value; break; case ax::mojom::BoolAttribute::kIsLineBreakingObject: result += " is_line_breaking_object=" + value; break; case ax::mojom::BoolAttribute::kIsPageBreakingObject: result += " is_page_breaking_object=" + value; break; case ax::mojom::BoolAttribute::kHasAriaAttribute: result += " has_aria_attribute=" + value; break; case ax::mojom::BoolAttribute::kNone: break; } } for (const std::pair<ax::mojom::IntListAttribute, std::vector<int32_t>>& intlist_attribute : intlist_attributes) { const std::vector<int32_t>& values = intlist_attribute.second; switch (intlist_attribute.first) { case ax::mojom::IntListAttribute::kIndirectChildIds: result += " indirect_child_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kControlsIds: result += " controls_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kDescribedbyIds: result += " describedby_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kDetailsIds: result += " details_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kFlowtoIds: result += " flowto_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kLabelledbyIds: result += " labelledby_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kRadioGroupIds: result += " radio_group_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kMarkerTypes: { std::string types_str; for (size_t i = 0; i < values.size(); ++i) { int32_t type = values[i]; if (type == static_cast<int32_t>(ax::mojom::MarkerType::kNone)) continue; if (i > 0) types_str += ','; if (type & static_cast<int32_t>(ax::mojom::MarkerType::kSpelling)) types_str += "spelling&"; if (type & static_cast<int32_t>(ax::mojom::MarkerType::kGrammar)) types_str += "grammar&"; if (type & static_cast<int32_t>(ax::mojom::MarkerType::kTextMatch)) types_str += "text_match&"; if (type & static_cast<int32_t>(ax::mojom::MarkerType::kActiveSuggestion)) types_str += "active_suggestion&"; if (type & static_cast<int32_t>(ax::mojom::MarkerType::kSuggestion)) types_str += "suggestion&"; if (!types_str.empty()) types_str = types_str.substr(0, types_str.size() - 1); } if (!types_str.empty()) result += " marker_types=" + types_str; break; } case ax::mojom::IntListAttribute::kMarkerStarts: result += " marker_starts=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kMarkerEnds: result += " marker_ends=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kCharacterOffsets: result += " character_offsets=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kCachedLineStarts: result += " cached_line_start_offsets=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kWordStarts: result += " word_starts=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kWordEnds: result += " word_ends=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kCustomActionIds: result += " custom_action_ids=" + IntVectorToString(values); break; case ax::mojom::IntListAttribute::kNone: break; } } for (const std::pair<ax::mojom::StringListAttribute, std::vector<std::string>>& stringlist_attribute : stringlist_attributes) { const std::vector<std::string>& values = stringlist_attribute.second; switch (stringlist_attribute.first) { case ax::mojom::StringListAttribute::kCustomActionDescriptions: result += " custom_action_descriptions: " + base::JoinString(values, ","); break; case ax::mojom::StringListAttribute::kNone: break; } } if (actions) result += " actions=" + ActionsBitfieldToString(actions); if (!child_ids.empty()) result += " child_ids=" + IntVectorToString(child_ids); return result; } std::string AXNodeData::DropeffectBitfieldToString() const { if (!HasIntAttribute(ax::mojom::IntAttribute::kDropeffect)) return ""; std::string str; for (int dropeffect_idx = static_cast<int>(ax::mojom::Dropeffect::kMinValue); dropeffect_idx <= static_cast<int>(ax::mojom::Dropeffect::kMaxValue); ++dropeffect_idx) { ax::mojom::Dropeffect dropeffect_enum = static_cast<ax::mojom::Dropeffect>(dropeffect_idx); if (HasDropeffect(dropeffect_enum)) str += " " + std::string(ui::ToString(dropeffect_enum)); } // Removing leading space in final string. return str.substr(1); } } // namespace ui
engine/third_party/accessibility/ax/ax_node_data.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_node_data.cc", "repo_id": "engine", "token_count": 26670 }
392
// 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 <unordered_set> #include "gtest/gtest.h" #include "ax_enum_util.h" #include "ax_enums.h" #include "ax_role_properties.h" namespace ui { TEST(AXRolePropertiesTest, TestSupportsHierarchicalLevel) { // Test for iterating through all roles and validate if a role supports // hierarchical level. std::unordered_set<ax::mojom::Role> roles_expected_supports_hierarchical_level = { ax::mojom::Role::kComment, ax::mojom::Role::kListItem, ax::mojom::Role::kRow, ax::mojom::Role::kTabList, ax::mojom::Role::kTreeItem}; for (int role_idx = static_cast<int>(ax::mojom::Role::kMinValue); role_idx <= static_cast<int>(ax::mojom::Role::kMaxValue); role_idx++) { ax::mojom::Role role = static_cast<ax::mojom::Role>(role_idx); bool supports_hierarchical_level = SupportsHierarchicalLevel(role); SCOPED_TRACE(testing::Message() << "ax::mojom::Role=" << ToString(role) << ", Actual: supportsHierarchicalLevel=" << supports_hierarchical_level << ", Expected: supportsHierarchicalLevel=" << !supports_hierarchical_level); if (roles_expected_supports_hierarchical_level.find(role) != roles_expected_supports_hierarchical_level.end()) EXPECT_TRUE(supports_hierarchical_level); else EXPECT_FALSE(supports_hierarchical_level); } } TEST(AXRolePropertiesTest, TestSupportsToggle) { // Test for iterating through all roles and validate if a role supports // toggle. std::unordered_set<ax::mojom::Role> roles_expected_supports_toggle = { ax::mojom::Role::kCheckBox, ax::mojom::Role::kMenuItemCheckBox, ax::mojom::Role::kSwitch, ax::mojom::Role::kToggleButton}; for (int role_idx = static_cast<int>(ax::mojom::Role::kMinValue); role_idx <= static_cast<int>(ax::mojom::Role::kMaxValue); role_idx++) { ax::mojom::Role role = static_cast<ax::mojom::Role>(role_idx); bool supports_toggle = SupportsToggle(role); SCOPED_TRACE(testing::Message() << "ax::mojom::Role=" << ToString(role) << ", Actual: supportsToggle=" << supports_toggle << ", Expected: supportsToggle=" << !supports_toggle); if (roles_expected_supports_toggle.find(role) != roles_expected_supports_toggle.end()) EXPECT_TRUE(supports_toggle); else EXPECT_FALSE(supports_toggle); } } } // namespace ui
engine/third_party/accessibility/ax/ax_role_properties_unittest.cc/0
{ "file_path": "engine/third_party/accessibility/ax/ax_role_properties_unittest.cc", "repo_id": "engine", "token_count": 1154 }
393
// 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_AX_TREE_OBSERVER_H_ #define UI_ACCESSIBILITY_AX_TREE_OBSERVER_H_ #include <cstdint> #include <string> #include <vector> #include "ax_enums.h" #include "ax_export.h" namespace ui { class AXNode; struct AXNodeData; class AXTree; struct AXTreeData; // Used when you want to be notified when changes happen to an AXTree. // // |OnAtomicUpdateFinished| is notified at the end of an atomic update. // It provides a vector of nodes that were added or changed, for final // postprocessing. class AX_EXPORT AXTreeObserver { public: AXTreeObserver(); virtual ~AXTreeObserver(); // Called before any tree modifications have occurred, notifying that a single // node will change its data. Its id and data will be valid, but its links to // parents and children are only valid within this callstack. Do not hold a // reference to the node or any relative nodes such as ancestors or // descendants described by the node data outside of this event. virtual void OnNodeDataWillChange(AXTree* tree, const AXNodeData& old_node_data, const AXNodeData& new_node_data) {} // Called after all tree modifications have occurred, notifying that a single // node has changed its data. Its id, data, and links to parent and children // will all be valid, since the tree is in a stable state after updating. virtual void OnNodeDataChanged(AXTree* tree, const AXNodeData& old_node_data, const AXNodeData& new_node_data) {} // Individual callbacks for every attribute of AXNodeData that can change. // Called after all tree mutations have occurred, notifying that a single node // changed its data. Its id, data, and links to parent and children will all // be valid, since the tree is in a stable state after updating. virtual void OnRoleChanged(AXTree* tree, AXNode* node, ax::mojom::Role old_role, ax::mojom::Role new_role) {} virtual void OnStateChanged(AXTree* tree, AXNode* node, ax::mojom::State state, bool new_value) {} virtual void OnStringAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::StringAttribute attr, const std::string& old_value, const std::string& new_value) {} virtual void OnIntAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::IntAttribute attr, int32_t old_value, int32_t new_value) {} virtual void OnFloatAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::FloatAttribute attr, float old_value, float new_value) {} virtual void OnBoolAttributeChanged(AXTree* tree, AXNode* node, ax::mojom::BoolAttribute attr, bool new_value) {} virtual void OnIntListAttributeChanged( AXTree* tree, AXNode* node, ax::mojom::IntListAttribute attr, const std::vector<int32_t>& old_value, const std::vector<int32_t>& new_value) {} virtual void OnStringListAttributeChanged( AXTree* tree, AXNode* node, ax::mojom::StringListAttribute attr, const std::vector<std::string>& old_value, const std::vector<std::string>& new_value) {} // Called when tree data changes, after all nodes have been updated. virtual void OnTreeDataChanged(AXTree* tree, const AXTreeData& old_data, const AXTreeData& new_data) {} // Called before any tree modifications have occurred, notifying that a single // node will be deleted. Its id and data will be valid, but its links to // parents and children are only valid within this callstack. Do not hold // a reference to node outside of the event. virtual void OnNodeWillBeDeleted(AXTree* tree, AXNode* node) {} // Same as OnNodeWillBeDeleted, but only called once for an entire subtree. virtual void OnSubtreeWillBeDeleted(AXTree* tree, AXNode* node) {} // Called just before a node is deleted for reparenting. See // |OnNodeWillBeDeleted| for additional information. virtual void OnNodeWillBeReparented(AXTree* tree, AXNode* node) {} // Called just before a subtree is deleted for reparenting. See // |OnSubtreeWillBeDeleted| for additional information. virtual void OnSubtreeWillBeReparented(AXTree* tree, AXNode* node) {} // Called after all tree mutations have occurred, notifying that a single node // has been created. Its id, data, and links to parent and children will all // be valid, since the tree is in a stable state after updating. virtual void OnNodeCreated(AXTree* tree, AXNode* node) {} // Called after all tree mutations have occurred or during tree teardown, // notifying that a single node has been deleted from the tree. virtual void OnNodeDeleted(AXTree* tree, int32_t node_id) {} // Same as |OnNodeCreated|, but called for nodes that have been reparented. virtual void OnNodeReparented(AXTree* tree, AXNode* node) {} // Called after all tree mutations have occurred, notifying that a single node // has updated its data or children. Its id, data, and links to parent and // children will all be valid, since the tree is in a stable state after // updating. virtual void OnNodeChanged(AXTree* tree, AXNode* node) {} enum ChangeType { NODE_CREATED, SUBTREE_CREATED, NODE_CHANGED, NODE_REPARENTED, SUBTREE_REPARENTED }; struct Change { Change(AXNode* node, ChangeType type) { this->node = node; this->type = type; } AXNode* node; ChangeType type; }; // Called at the end of the update operation. Every node that was added // or changed will be included in |changes|, along with an enum indicating // the type of change - either (1) a node was created, (2) a node was created // and it's the root of a new subtree, or (3) a node was changed. Finally, // a bool indicates if the root of the tree was changed or not. virtual void OnAtomicUpdateFinished(AXTree* tree, bool root_changed, const std::vector<Change>& changes) {} }; } // namespace ui #endif // UI_ACCESSIBILITY_AX_TREE_OBSERVER_H_
engine/third_party/accessibility/ax/ax_tree_observer.h/0
{ "file_path": "engine/third_party/accessibility/ax/ax_tree_observer.h", "repo_id": "engine", "token_count": 2879 }
394
// 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_PLATFORM_AX_PLATFORM_NODE_DELEGATE_UTILS_WIN_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_UTILS_WIN_H_ #include "ax/ax_export.h" namespace ui { class AXPlatformNodeDelegate; // Returns true if the value pattern is supported AX_EXPORT bool IsValuePatternSupported(AXPlatformNodeDelegate*); } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_UTILS_WIN_H_
engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.h/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_delegate_utils_win.h", "repo_id": "engine", "token_count": 218 }
395
// 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_PLATFORM_AX_PLATFORM_NODE_WIN_UNITTEST_H_ #define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_WIN_UNITTEST_H_ #include "ax_platform_node_unittest.h" // clang-format off #include "third_party/accessibility/base/win/atl.h" // Must be before UIAutomationCore.h // clang-format on #include <UIAutomationCore.h> #include <wrl.h> #include <memory> #include <string> #include <unordered_set> #include "third_party/accessibility/ax/platform/ax_fragment_root_delegate_win.h" struct IAccessible; struct IAccessibleTableCell; struct IRawElementProviderFragment; struct IRawElementProviderFragmentRoot; struct IRawElementProviderSimple; struct IUnknown; namespace base { namespace win { class ScopedVariant; } // namespace win } // namespace base namespace ui { class AXFragmentRootWin; class AXPlatformNode; class TestFragmentRootDelegate : public AXFragmentRootDelegateWin { public: TestFragmentRootDelegate(); virtual ~TestFragmentRootDelegate(); gfx::NativeViewAccessible GetChildOfAXFragmentRoot() override; gfx::NativeViewAccessible GetParentOfAXFragmentRoot() override; bool IsAXFragmentRootAControlElement() override; gfx::NativeViewAccessible child_ = nullptr; gfx::NativeViewAccessible parent_ = nullptr; bool is_control_element_ = true; }; class MockIRawElementProviderSimple : public CComObjectRootEx<CComMultiThreadModel>, public IRawElementProviderSimple { public: BEGIN_COM_MAP(MockIRawElementProviderSimple) COM_INTERFACE_ENTRY(IRawElementProviderSimple) END_COM_MAP() MockIRawElementProviderSimple(); ~MockIRawElementProviderSimple(); static HRESULT CreateMockIRawElementProviderSimple( IRawElementProviderSimple** provider); // // IRawElementProviderSimple methods. // IFACEMETHODIMP GetPatternProvider(PATTERNID pattern_id, IUnknown** result) override; IFACEMETHODIMP GetPropertyValue(PROPERTYID property_id, VARIANT* result) override; IFACEMETHODIMP get_ProviderOptions(enum ProviderOptions* ret) override; IFACEMETHODIMP get_HostRawElementProvider(IRawElementProviderSimple** provider) override; }; class AXPlatformNodeWinTest : public AXPlatformNodeTest { public: AXPlatformNodeWinTest(); ~AXPlatformNodeWinTest() override; void SetUp() override; void TearDown() override; protected: static const std::u16string kEmbeddedCharacterAsString; AXPlatformNode* AXPlatformNodeFromNode(AXNode* node); template <typename T> Microsoft::WRL::ComPtr<T> QueryInterfaceFromNodeId(AXNode::AXID id); template <typename T> Microsoft::WRL::ComPtr<T> QueryInterfaceFromNode(AXNode* node); Microsoft::WRL::ComPtr<IRawElementProviderSimple> GetRootIRawElementProviderSimple(); Microsoft::WRL::ComPtr<IRawElementProviderSimple> GetIRawElementProviderSimpleFromChildIndex(int child_index); Microsoft::WRL::ComPtr<IRawElementProviderSimple> GetIRawElementProviderSimpleFromTree(const ui::AXTreeID tree_id, const AXNode::AXID node_id); Microsoft::WRL::ComPtr<IRawElementProviderFragment> GetRootIRawElementProviderFragment(); Microsoft::WRL::ComPtr<IRawElementProviderFragment> IRawElementProviderFragmentFromNode(AXNode* node); Microsoft::WRL::ComPtr<IAccessible> IAccessibleFromNode(AXNode* node); Microsoft::WRL::ComPtr<IAccessible> GetRootIAccessible(); void CheckVariantHasName(const base::win::ScopedVariant& variant, const wchar_t* expected_name); void CheckIUnknownHasName(Microsoft::WRL::ComPtr<IUnknown> unknown, const wchar_t* expected_name); Microsoft::WRL::ComPtr<IAccessibleTableCell> GetCellInTable(); void InitFragmentRoot(); AXFragmentRootWin* InitNodeAsFragmentRoot(AXNode* node, TestFragmentRootDelegate* delegate); Microsoft::WRL::ComPtr<IRawElementProviderFragmentRoot> GetFragmentRoot(); using PatternSet = std::unordered_set<LONG>; PatternSet GetSupportedPatternsFromNodeId(AXNode::AXID id); std::unique_ptr<AXFragmentRootWin> ax_fragment_root_; std::unique_ptr<TestFragmentRootDelegate> test_fragment_root_delegate_; }; } // namespace ui #endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_WIN_UNITTEST_H_
engine/third_party/accessibility/ax/platform/ax_platform_node_win_unittest.h/0
{ "file_path": "engine/third_party/accessibility/ax/platform/ax_platform_node_win_unittest.h", "repo_id": "engine", "token_count": 1590 }
396
// 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 ACCESSIBILITY_TEST_AX_AX_TREE_MANAGER_H_ #define ACCESSIBILITY_TEST_AX_AX_TREE_MANAGER_H_ #include <memory> #include "ax_tree.h" #include "ax_tree_id.h" #include "ax_tree_manager.h" namespace ui { class AXNode; // A basic implementation of AXTreeManager that can be used in tests. // // For simplicity, this class supports only a single tree and doesn't perform // any walking across multiple trees. class TestAXTreeManager : public AXTreeManager { public: // This constructor does not create an empty AXTree. Call "SetTree" if you // need to manage a specific tree. Useful when you need to test for the // situation when no AXTree has been loaded yet. TestAXTreeManager(); // Takes ownership of |tree|. explicit TestAXTreeManager(std::unique_ptr<AXTree> tree); virtual ~TestAXTreeManager(); TestAXTreeManager(const TestAXTreeManager& manager) = delete; TestAXTreeManager& operator=(const TestAXTreeManager& manager) = delete; void DestroyTree(); AXTree* GetTree() const; // Takes ownership of |tree|. void SetTree(std::unique_ptr<AXTree> tree); // AXTreeManager implementation. AXNode* GetNodeFromTree(const AXTreeID tree_id, const AXNode::AXID node_id) const override; AXNode* GetNodeFromTree(const AXNode::AXID node_id) const override; AXTreeID GetTreeID() const override; AXTreeID GetParentTreeID() const override; AXNode* GetRootAsAXNode() const override; AXNode* GetParentNodeFromParentTreeAsAXNode() const override; private: std::unique_ptr<AXTree> tree_; }; } // namespace ui #endif // ACCESSIBILITY_TEST_AX_AX_TREE_MANAGER_H_
engine/third_party/accessibility/ax/test_ax_tree_manager.h/0
{ "file_path": "engine/third_party/accessibility/ax/test_ax_tree_manager.h", "repo_id": "engine", "token_count": 601 }
397
// 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 BASE_NUMERICS_CHECKED_MATH_H_ #define BASE_NUMERICS_CHECKED_MATH_H_ #include <cstddef> #include <limits> #include <type_traits> #include "base/numerics/checked_math_impl.h" namespace base { namespace internal { template <typename T> class CheckedNumeric { static_assert(std::is_arithmetic<T>::value, "CheckedNumeric<T>: T must be a numeric type."); public: using type = T; constexpr CheckedNumeric() = default; // Copy constructor. template <typename Src> constexpr CheckedNumeric(const CheckedNumeric<Src>& rhs) : state_(rhs.state_.value(), rhs.IsValid()) {} template <typename Src> friend class CheckedNumeric; // This is not an explicit constructor because we implicitly upgrade regular // numerics to CheckedNumerics to make them easier to use. template <typename Src> constexpr CheckedNumeric(Src value) // NOLINT(runtime/explicit) : state_(value) { static_assert(std::is_arithmetic<Src>::value, "Argument must be numeric."); } // This is not an explicit constructor because we want a seamless conversion // from StrictNumeric types. template <typename Src> constexpr CheckedNumeric( StrictNumeric<Src> value) // NOLINT(runtime/explicit) : state_(static_cast<Src>(value)) {} // IsValid() - The public API to test if a CheckedNumeric is currently valid. // A range checked destination type can be supplied using the Dst template // parameter. template <typename Dst = T> constexpr bool IsValid() const { return state_.is_valid() && IsValueInRangeForNumericType<Dst>(state_.value()); } // AssignIfValid(Dst) - Assigns the underlying value if it is currently valid // and is within the range supported by the destination type. Returns true if // successful and false otherwise. template <typename Dst> #if defined(__clang__) || defined(__GNUC__) __attribute__((warn_unused_result)) #elif defined(_MSC_VER) _Check_return_ #endif constexpr bool AssignIfValid(Dst* result) const { return BASE_NUMERICS_LIKELY(IsValid<Dst>()) ? ((*result = static_cast<Dst>(state_.value())), true) : false; } // ValueOrDie() - The primary accessor for the underlying value. If the // current state is not valid it will CHECK and crash. // A range checked destination type can be supplied using the Dst template // parameter, which will trigger a CHECK if the value is not in bounds for // the destination. // The CHECK behavior can be overridden by supplying a handler as a // template parameter, for test code, etc. However, the handler cannot access // the underlying value, and it is not available through other means. template <typename Dst = T, class CheckHandler = CheckOnFailure> constexpr StrictNumeric<Dst> ValueOrDie() const { return BASE_NUMERICS_LIKELY(IsValid<Dst>()) ? static_cast<Dst>(state_.value()) : CheckHandler::template HandleFailure<Dst>(); } // ValueOrDefault(T default_value) - A convenience method that returns the // current value if the state is valid, and the supplied default_value for // any other state. // A range checked destination type can be supplied using the Dst template // parameter. WARNING: This function may fail to compile or CHECK at runtime // if the supplied default_value is not within range of the destination type. template <typename Dst = T, typename Src> constexpr StrictNumeric<Dst> ValueOrDefault(const Src default_value) const { return BASE_NUMERICS_LIKELY(IsValid<Dst>()) ? static_cast<Dst>(state_.value()) : checked_cast<Dst>(default_value); } // Returns a checked numeric of the specified type, cast from the current // CheckedNumeric. If the current state is invalid or the destination cannot // represent the result then the returned CheckedNumeric will be invalid. template <typename Dst> constexpr CheckedNumeric<typename UnderlyingType<Dst>::type> Cast() const { return *this; } // This friend method is available solely for providing more detailed logging // in the tests. Do not implement it in production code, because the // underlying values may change at any time. template <typename U> friend U GetNumericValueForTest(const CheckedNumeric<U>& src); // Prototypes for the supported arithmetic operator overloads. template <typename Src> constexpr CheckedNumeric& operator+=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator-=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator*=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator/=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator%=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator<<=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator>>=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator&=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator|=(const Src rhs); template <typename Src> constexpr CheckedNumeric& operator^=(const Src rhs); constexpr CheckedNumeric operator-() const { // The negation of two's complement int min is int min, so we simply // check for that in the constexpr case. // We use an optimized code path for a known run-time variable. return MustTreatAsConstexpr(state_.value()) || !std::is_signed<T>::value || std::is_floating_point<T>::value ? CheckedNumeric<T>( NegateWrapper(state_.value()), IsValid() && (!std::is_signed<T>::value || std::is_floating_point<T>::value || NegateWrapper(state_.value()) != std::numeric_limits<T>::lowest())) : FastRuntimeNegate(); } constexpr CheckedNumeric operator~() const { return CheckedNumeric<decltype(InvertWrapper(T()))>( InvertWrapper(state_.value()), IsValid()); } constexpr CheckedNumeric Abs() const { return !IsValueNegative(state_.value()) ? *this : -*this; } template <typename U> constexpr CheckedNumeric<typename MathWrapper<CheckedMaxOp, T, U>::type> Max( const U rhs) const { using R = typename UnderlyingType<U>::type; using result_type = typename MathWrapper<CheckedMaxOp, T, U>::type; // TODO(jschuh): This can be converted to the MathOp version and remain // constexpr once we have C++14 support. return CheckedNumeric<result_type>( static_cast<result_type>( IsGreater<T, R>::Test(state_.value(), Wrapper<U>::value(rhs)) ? state_.value() : Wrapper<U>::value(rhs)), state_.is_valid() && Wrapper<U>::is_valid(rhs)); } template <typename U> constexpr CheckedNumeric<typename MathWrapper<CheckedMinOp, T, U>::type> Min( const U rhs) const { using R = typename UnderlyingType<U>::type; using result_type = typename MathWrapper<CheckedMinOp, T, U>::type; // TODO(jschuh): This can be converted to the MathOp version and remain // constexpr once we have C++14 support. return CheckedNumeric<result_type>( static_cast<result_type>( IsLess<T, R>::Test(state_.value(), Wrapper<U>::value(rhs)) ? state_.value() : Wrapper<U>::value(rhs)), state_.is_valid() && Wrapper<U>::is_valid(rhs)); } // This function is available only for integral types. It returns an unsigned // integer of the same width as the source type, containing the absolute value // of the source, and properly handling signed min. constexpr CheckedNumeric<typename UnsignedOrFloatForSize<T>::type> UnsignedAbs() const { return CheckedNumeric<typename UnsignedOrFloatForSize<T>::type>( SafeUnsignedAbs(state_.value()), state_.is_valid()); } constexpr CheckedNumeric& operator++() { *this += 1; return *this; } constexpr CheckedNumeric operator++(int) { CheckedNumeric value = *this; *this += 1; return value; } constexpr CheckedNumeric& operator--() { *this -= 1; return *this; } constexpr CheckedNumeric operator--(int) { CheckedNumeric value = *this; *this -= 1; return value; } // These perform the actual math operations on the CheckedNumerics. // Binary arithmetic operations. template <template <typename, typename, typename> class M, typename L, typename R> static constexpr CheckedNumeric MathOp(const L lhs, const R rhs) { using Math = typename MathWrapper<M, L, R>::math; T result = 0; bool is_valid = Wrapper<L>::is_valid(lhs) && Wrapper<R>::is_valid(rhs) && Math::Do(Wrapper<L>::value(lhs), Wrapper<R>::value(rhs), &result); return CheckedNumeric<T>(result, is_valid); } // Assignment arithmetic operations. template <template <typename, typename, typename> class M, typename R> constexpr CheckedNumeric& MathOp(const R rhs) { using Math = typename MathWrapper<M, T, R>::math; T result = 0; // Using T as the destination saves a range check. bool is_valid = state_.is_valid() && Wrapper<R>::is_valid(rhs) && Math::Do(state_.value(), Wrapper<R>::value(rhs), &result); *this = CheckedNumeric<T>(result, is_valid); return *this; } private: CheckedNumericState<T> state_; CheckedNumeric FastRuntimeNegate() const { T result; bool success = CheckedSubOp<T, T>::Do(T(0), state_.value(), &result); return CheckedNumeric<T>(result, IsValid() && success); } template <typename Src> constexpr CheckedNumeric(Src value, bool is_valid) : state_(value, is_valid) {} // These wrappers allow us to handle state the same way for both // CheckedNumeric and POD arithmetic types. template <typename Src> struct Wrapper { static constexpr bool is_valid(Src) { return true; } static constexpr Src value(Src value) { return value; } }; template <typename Src> struct Wrapper<CheckedNumeric<Src>> { static constexpr bool is_valid(const CheckedNumeric<Src> v) { return v.IsValid(); } static constexpr Src value(const CheckedNumeric<Src> v) { return v.state_.value(); } }; template <typename Src> struct Wrapper<StrictNumeric<Src>> { static constexpr bool is_valid(const StrictNumeric<Src>) { return true; } static constexpr Src value(const StrictNumeric<Src> v) { return static_cast<Src>(v); } }; }; // Convenience functions to avoid the ugly template disambiguator syntax. template <typename Dst, typename Src> constexpr bool IsValidForType(const CheckedNumeric<Src> value) { return value.template IsValid<Dst>(); } template <typename Dst, typename Src> constexpr StrictNumeric<Dst> ValueOrDieForType( const CheckedNumeric<Src> value) { return value.template ValueOrDie<Dst>(); } template <typename Dst, typename Src, typename Default> constexpr StrictNumeric<Dst> ValueOrDefaultForType( const CheckedNumeric<Src> value, const Default default_value) { return value.template ValueOrDefault<Dst>(default_value); } // Convience wrapper to return a new CheckedNumeric from the provided arithmetic // or CheckedNumericType. template <typename T> constexpr CheckedNumeric<typename UnderlyingType<T>::type> MakeCheckedNum( const T value) { return value; } // These implement the variadic wrapper for the math operations. template <template <typename, typename, typename> class M, typename L, typename R> constexpr CheckedNumeric<typename MathWrapper<M, L, R>::type> CheckMathOp( const L lhs, const R rhs) { using Math = typename MathWrapper<M, L, R>::math; return CheckedNumeric<typename Math::result_type>::template MathOp<M>(lhs, rhs); } // General purpose wrapper template for arithmetic operations. template <template <typename, typename, typename> class M, typename L, typename R, typename... Args> constexpr CheckedNumeric<typename ResultType<M, L, R, Args...>::type> CheckMathOp(const L lhs, const R rhs, const Args... args) { return CheckMathOp<M>(CheckMathOp<M>(lhs, rhs), args...); } BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Add, +, +=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Sub, -, -=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mul, *, *=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Div, /, /=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Mod, %, %=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Lsh, <<, <<=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Rsh, >>, >>=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, And, &, &=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Or, |, |=) BASE_NUMERIC_ARITHMETIC_OPERATORS(Checked, Check, Xor, ^, ^=) BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Max) BASE_NUMERIC_ARITHMETIC_VARIADIC(Checked, Check, Min) // These are some extra StrictNumeric operators to support simple pointer // arithmetic with our result types. Since wrapping on a pointer is always // bad, we trigger the CHECK condition here. template <typename L, typename R> L* operator+(L* lhs, const StrictNumeric<R> rhs) { uintptr_t result = CheckAdd(reinterpret_cast<uintptr_t>(lhs), CheckMul(sizeof(L), static_cast<R>(rhs))) .template ValueOrDie<uintptr_t>(); return reinterpret_cast<L*>(result); } template <typename L, typename R> L* operator-(L* lhs, const StrictNumeric<R> rhs) { uintptr_t result = CheckSub(reinterpret_cast<uintptr_t>(lhs), CheckMul(sizeof(L), static_cast<R>(rhs))) .template ValueOrDie<uintptr_t>(); return reinterpret_cast<L*>(result); } } // namespace internal using internal::CheckAdd; using internal::CheckAnd; using internal::CheckDiv; using internal::CheckedNumeric; using internal::CheckLsh; using internal::CheckMax; using internal::CheckMin; using internal::CheckMod; using internal::CheckMul; using internal::CheckOr; using internal::CheckRsh; using internal::CheckSub; using internal::CheckXor; using internal::IsValidForType; using internal::MakeCheckedNum; using internal::ValueOrDefaultForType; using internal::ValueOrDieForType; } // namespace base #endif // BASE_NUMERICS_CHECKED_MATH_H_
engine/third_party/accessibility/base/numerics/checked_math.h/0
{ "file_path": "engine/third_party/accessibility/base/numerics/checked_math.h", "repo_id": "engine", "token_count": 5476 }
398
// 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_SIMPLE_TOKEN_H_ #define BASE_SIMPLE_TOKEN_H_ #include <functional> #include <optional> #include <string> namespace base { // A simple string wrapping token. class SimpleToken { public: // Create a random SimpleToken. static SimpleToken Create(); // Creates an empty SimpleToken. // Assign to it with Create() before using it. SimpleToken() = default; ~SimpleToken() = default; // Creates an token that wrapps the input string. SimpleToken(const std::string& token); // Hex representation of the unguessable token. std::string ToString() const { return token_; } explicit constexpr operator bool() const { return !token_.empty(); } constexpr bool operator<(const SimpleToken& other) const { return token_.compare(other.token_) < 0; } constexpr bool operator==(const SimpleToken& other) const { return token_.compare(other.token_) == 0; } constexpr bool operator!=(const SimpleToken& other) const { return !(*this == other); } private: std::string token_; }; std::ostream& operator<<(std::ostream& out, const SimpleToken& token); std::optional<base::SimpleToken> ValueToSimpleToken(std::string str); std::string SimpleTokenToValue(const SimpleToken& token); size_t SimpleTokenHash(const SimpleToken& SimpleToken); } // namespace base #endif // BASE_SIMPLE_TOKEN_H_
engine/third_party/accessibility/base/simple_token.h/0
{ "file_path": "engine/third_party/accessibility/base/simple_token.h", "repo_id": "engine", "token_count": 456 }
399
// Copyright (c) 2011 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_SCOPED_BSTR_H_ #define BASE_WIN_SCOPED_BSTR_H_ #include <windows.h> #include <oleauto.h> #include <cstddef> #include "base/base_export.h" #include "base/logging.h" namespace base { namespace win { // Manages a BSTR string pointer. // The class interface is based on unique_ptr. class BASE_EXPORT ScopedBstr { public: ScopedBstr() = default; // Constructor to create a new BSTR. // // NOTE: Do not pass a BSTR to this constructor expecting ownership to // be transferred - even though it compiles! ;-) explicit ScopedBstr(std::wstring_view non_bstr); ~ScopedBstr(); BSTR Get() const { return bstr_; } // Give ScopedBstr ownership over an already allocated BSTR or null. // If you need to allocate a new BSTR instance, use |allocate| instead. void Reset(BSTR bstr = nullptr); // Releases ownership of the BSTR to the caller. BSTR Release(); // Creates a new BSTR from a 16-bit C-style string. // // If you already have a BSTR and want to transfer ownership to the // ScopedBstr instance, call |reset| instead. // // Returns a pointer to the new BSTR. BSTR Allocate(std::wstring_view str); // Allocates a new BSTR with the specified number of bytes. // Returns a pointer to the new BSTR. BSTR AllocateBytes(size_t bytes); // Sets the allocated length field of the already-allocated BSTR to be // |bytes|. This is useful when the BSTR was preallocated with e.g. // SysAllocStringLen or SysAllocStringByteLen (call |AllocateBytes|) and then // not all the bytes are being used. // // Note that if you want to set the length to a specific number of // characters, you need to multiply by sizeof(wchar_t). Oddly, there's no // public API to set the length, so we do this ourselves by hand. // // NOTE: The actual allocated size of the BSTR MUST be >= bytes. That // responsibility is with the caller. void SetByteLen(size_t bytes); // Swap values of two ScopedBstr's. void Swap(ScopedBstr& bstr2); // Retrieves the pointer address. // Used to receive BSTRs as out arguments (and take ownership). // The function DCHECKs on the current value being null. // Usage: GetBstr(bstr.Receive()); BSTR* Receive(); // Returns number of chars in the BSTR. size_t Length() const; // Returns the number of bytes allocated for the BSTR. size_t ByteLength() const; // Forbid comparison of ScopedBstr types. You should never have the same // BSTR owned by two different scoped_ptrs. bool operator==(const ScopedBstr& bstr2) const = delete; bool operator!=(const ScopedBstr& bstr2) const = delete; private: BSTR bstr_ = nullptr; BASE_DISALLOW_COPY_AND_ASSIGN(ScopedBstr); }; } // namespace win } // namespace base #endif // BASE_WIN_SCOPED_BSTR_H_
engine/third_party/accessibility/base/win/scoped_bstr.h/0
{ "file_path": "engine/third_party/accessibility/base/win/scoped_bstr.h", "repo_id": "engine", "token_count": 942 }
400
// 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. #ifndef UI_GFX_GEOMETRY_INSETS_F_H_ #define UI_GFX_GEOMETRY_INSETS_F_H_ #include <string> #include "gfx/gfx_export.h" namespace gfx { // A floating point version of gfx::Insets. class GFX_EXPORT InsetsF { public: constexpr InsetsF() : top_(0.f), left_(0.f), bottom_(0.f), right_(0.f) {} constexpr explicit InsetsF(float all) : top_(all), left_(all), bottom_(all), right_(all) {} constexpr InsetsF(float vertical, float horizontal) : top_(vertical), left_(horizontal), bottom_(vertical), right_(horizontal) {} constexpr InsetsF(float top, float left, float bottom, float right) : top_(top), left_(left), bottom_(bottom), right_(right) {} constexpr float top() const { return top_; } constexpr float left() const { return left_; } constexpr float bottom() const { return bottom_; } constexpr float right() const { return right_; } // Returns the total width taken up by the insets, which is the sum of the // left and right insets. constexpr float width() const { return left_ + right_; } // Returns the total height taken up by the insets, which is the sum of the // top and bottom insets. constexpr float height() const { return top_ + bottom_; } // Returns true if the insets are empty. bool IsEmpty() const { return width() == 0.f && height() == 0.f; } void Set(float top, float left, float bottom, float right) { top_ = top; left_ = left; bottom_ = bottom; right_ = right; } bool operator==(const InsetsF& insets) const { return top_ == insets.top_ && left_ == insets.left_ && bottom_ == insets.bottom_ && right_ == insets.right_; } bool operator!=(const InsetsF& insets) const { return !(*this == insets); } void operator+=(const InsetsF& insets) { top_ += insets.top_; left_ += insets.left_; bottom_ += insets.bottom_; right_ += insets.right_; } void operator-=(const InsetsF& insets) { top_ -= insets.top_; left_ -= insets.left_; bottom_ -= insets.bottom_; right_ -= insets.right_; } InsetsF operator-() const { return InsetsF(-top_, -left_, -bottom_, -right_); } InsetsF Scale(float scale) const { return InsetsF(scale * top(), scale * left(), scale * bottom(), scale * right()); } // Returns a string representation of the insets. std::string ToString() const; private: float top_; float left_; float bottom_; float right_; }; inline InsetsF operator+(InsetsF lhs, const InsetsF& rhs) { lhs += rhs; return lhs; } inline InsetsF operator-(InsetsF lhs, const InsetsF& rhs) { lhs -= rhs; return lhs; } } // namespace gfx #endif // UI_GFX_GEOMETRY_INSETS_F_H_
engine/third_party/accessibility/gfx/geometry/insets_f.h/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/insets_f.h", "repo_id": "engine", "token_count": 1057 }
401
// 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 "size.h" #if defined(OS_WIN) #include <windows.h> #elif defined(OS_IOS) #include <CoreGraphics/CoreGraphics.h> #elif defined(OS_APPLE) #include <ApplicationServices/ApplicationServices.h> #endif #include "ax_build/build_config.h" #include "base/numerics/clamped_math.h" #include "base/numerics/safe_math.h" #include "base/string_utils.h" #include "size_conversions.h" namespace gfx { #if defined(OS_APPLE) Size::Size(const CGSize& s) : width_(s.width < 0 ? 0 : s.width), height_(s.height < 0 ? 0 : s.height) {} Size& Size::operator=(const CGSize& s) { set_width(s.width); set_height(s.height); return *this; } #endif void Size::operator+=(const Size& size) { Enlarge(size.width(), size.height()); } void Size::operator-=(const Size& size) { Enlarge(-size.width(), -size.height()); } #if defined(OS_WIN) SIZE Size::ToSIZE() const { SIZE s; s.cx = width(); s.cy = height(); return s; } #elif defined(OS_APPLE) CGSize Size::ToCGSize() const { return CGSizeMake(width(), height()); } #endif int Size::GetArea() const { return GetCheckedArea().ValueOrDie(); } base::CheckedNumeric<int> Size::GetCheckedArea() const { base::CheckedNumeric<int> checked_area = width(); checked_area *= height(); return checked_area; } void Size::Enlarge(int grow_width, int grow_height) { SetSize(base::ClampAdd(width(), grow_width), base::ClampAdd(height(), grow_height)); } void Size::SetToMin(const Size& other) { width_ = width() <= other.width() ? width() : other.width(); height_ = height() <= other.height() ? height() : other.height(); } void Size::SetToMax(const Size& other) { width_ = width() >= other.width() ? width() : other.width(); height_ = height() >= other.height() ? height() : other.height(); } std::string Size::ToString() const { return base::StringPrintf("%dx%d", width(), height()); } Size ScaleToCeiledSize(const Size& size, float x_scale, float y_scale) { if (x_scale == 1.f && y_scale == 1.f) return size; return ToCeiledSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale)); } Size ScaleToCeiledSize(const Size& size, float scale) { if (scale == 1.f) return size; return ToCeiledSize(ScaleSize(gfx::SizeF(size), scale, scale)); } Size ScaleToFlooredSize(const Size& size, float x_scale, float y_scale) { if (x_scale == 1.f && y_scale == 1.f) return size; return ToFlooredSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale)); } Size ScaleToFlooredSize(const Size& size, float scale) { if (scale == 1.f) return size; return ToFlooredSize(ScaleSize(gfx::SizeF(size), scale, scale)); } Size ScaleToRoundedSize(const Size& size, float x_scale, float y_scale) { if (x_scale == 1.f && y_scale == 1.f) return size; return ToRoundedSize(ScaleSize(gfx::SizeF(size), x_scale, y_scale)); } Size ScaleToRoundedSize(const Size& size, float scale) { if (scale == 1.f) return size; return ToRoundedSize(ScaleSize(gfx::SizeF(size), scale, scale)); } } // namespace gfx
engine/third_party/accessibility/gfx/geometry/size.cc/0
{ "file_path": "engine/third_party/accessibility/gfx/geometry/size.cc", "repo_id": "engine", "token_count": 1165 }
402
// 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. #import "coordinate_conversion.h" #import <Cocoa/Cocoa.h> #include "gfx/geometry/point.h" #include "gfx/geometry/rect.h" namespace gfx { namespace { // The height of the primary display, which OSX defines as the monitor with the // menubar. This is always at index 0. CGFloat PrimaryDisplayHeight() { return NSMaxY([[[NSScreen screens] firstObject] frame]); } } // namespace NSRect ScreenRectToNSRect(const Rect& rect) { return NSMakeRect(rect.x(), PrimaryDisplayHeight() - rect.y() - rect.height(), rect.width(), rect.height()); } Rect ScreenRectFromNSRect(const NSRect& rect) { return Rect(rect.origin.x, PrimaryDisplayHeight() - rect.origin.y - rect.size.height, rect.size.width, rect.size.height); } NSPoint ScreenPointToNSPoint(const Point& point) { return NSMakePoint(point.x(), PrimaryDisplayHeight() - point.y()); } Point ScreenPointFromNSPoint(const NSPoint& point) { return Point(point.x, PrimaryDisplayHeight() - point.y); } } // namespace gfx
engine/third_party/accessibility/gfx/mac/coordinate_conversion.mm/0
{ "file_path": "engine/third_party/accessibility/gfx/mac/coordinate_conversion.mm", "repo_id": "engine", "token_count": 406 }
403
# spring_animation This is directly derived from [Libraries/Animated/animations/SpringAnimation.js](https://github.com/facebook/react-native/blob/494c47360f62761176033a4da359f43b53c2182f/Libraries/Animated/animations/SpringAnimation.js) as of 2023-01-10, a part of the React Native library.
engine/third_party/spring_animation/README.md/0
{ "file_path": "engine/third_party/spring_animation/README.md", "repo_id": "engine", "token_count": 99 }
404
// 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_persistent_value.h" #include "tonic/dart_state.h" #include "tonic/scopes/dart_isolate_scope.h" namespace tonic { DartPersistentValue::DartPersistentValue() : value_(nullptr) {} DartPersistentValue::DartPersistentValue(DartPersistentValue&& other) : dart_state_(other.dart_state_), value_(other.value_) { other.dart_state_.reset(); other.value_ = nullptr; } DartPersistentValue::DartPersistentValue(DartState* dart_state, Dart_Handle value) : value_(nullptr) { Set(dart_state, value); } DartPersistentValue::~DartPersistentValue() { Clear(); } void DartPersistentValue::Set(DartState* dart_state, Dart_Handle value) { TONIC_DCHECK(is_empty()); dart_state_ = dart_state->GetWeakPtr(); value_ = Dart_NewPersistentHandle(value); } void DartPersistentValue::Clear() { if (!value_) { return; } auto dart_state = dart_state_.lock(); if (!dart_state) { // The Dart isolate was collected and the persistent value has been // collected with it. value_ is a dangling reference. value_ = nullptr; return; } /// TODO(80155): Remove the handle even if the isolate is shutting down. This /// may cause memory to stick around until the isolate group is destroyed. /// Without this branch, if DartState::IsShuttingDown == true, this code will /// crash when binding the isolate. if (!dart_state->IsShuttingDown()) { if (Dart_CurrentIsolateGroup()) { Dart_DeletePersistentHandle(value_); } else { DartIsolateScope scope(dart_state->isolate()); Dart_DeletePersistentHandle(value_); } } dart_state_.reset(); value_ = nullptr; } Dart_Handle DartPersistentValue::Get() { if (!value_) return nullptr; return Dart_HandleFromPersistent(value_); } Dart_Handle DartPersistentValue::Release() { Dart_Handle local = Get(); Clear(); return local; } } // namespace tonic
engine/third_party/tonic/dart_persistent_value.cc/0
{ "file_path": "engine/third_party/tonic/dart_persistent_value.cc", "repo_id": "engine", "token_count": 744 }
405
Files ===== A simple cross-platform library with minimal dependencies to work with files and paths.
engine/third_party/tonic/filesystem/README.md/0
{ "file_path": "engine/third_party/tonic/filesystem/README.md", "repo_id": "engine", "token_count": 22 }
406
// 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_LOGGING_DART_ERROR_H_ #define LIB_TONIC_LOGGING_DART_ERROR_H_ #include "third_party/dart/runtime/include/dart_api.h" #include "tonic/dart_persistent_value.h" namespace tonic { namespace DartError { using UnhandledExceptionReporter = void (*)(Dart_Handle, Dart_Handle); extern const char kInvalidArgument[]; } // namespace DartError /// Check if a Dart_Handle is an error or exception. /// /// If it is an error or exception, this method will return true. /// /// If it is an unhandled error or exception, the closure in /// |SetUnhandledExceptionReporter| is called. The DartVMInitializer provides /// that closure, which checks with UIDartState::Current() if it is available /// and falls back to simply printing the exception and stack to an error log if /// the settings callback is not provided. /// /// If UIDartState::Current() is available, it can provide an onError callback /// that forwards to `PlatformConfiguration.instance.onError`. If that callback /// is not set, the callback from `Settings.unhandled_exception_callback` is /// invoked. If that callback is not set, a simple error log is /// printed. /// /// If the PlatformDispatcher callback throws an exception, the at least two /// separate exceptions and stacktraces will be handled by either the /// Settings.unhandled_exception_callback or the error printer: one for the /// original exception, and one for the exception thrown in the callback. If the /// callback returns false, the original exception and stacktrace are logged. If /// it returns true, no additional logging is done. /// /// Leaving the PlatformDispatcher.instance.onError callback unset or returning /// false from it matches the behavior of Flutter applications before the /// introduction of PlatformDispatcher.onError, which is to print to the error /// log. /// /// Dart has errors that are not considered unhandled exceptions, such as /// Dart_* API usage errors. In these cases, `Dart_IsUnhandledException` returns /// false but `Dart_IsError` returns true. Such errors are logged to stderr or /// some similar mechanism provided by the platform such as logcat on Android. /// Depending on which type of error occurs, the process may crash and the Dart /// isolate may be unusable. Errors that fall into this category include /// compilation errors, Dart API errors, and unwind errors that will terminate /// the Dart VM. /// /// Historically known as LogIfError. bool CheckAndHandleError(Dart_Handle handle); /// The fallback mechanism to log errors if the platform configuration error /// handler returns false. /// /// Normally, UIDartState registers with this method in its constructor. void SetUnhandledExceptionReporter( DartError::UnhandledExceptionReporter reporter); enum DartErrorHandleType { kNoError, kUnknownErrorType, kApiErrorType, kCompilationErrorType, }; DartErrorHandleType GetErrorHandleType(Dart_Handle handle); int GetErrorExitCode(Dart_Handle handle); } // namespace tonic #endif // LIB_TONIC_DART_ERROR_H_
engine/third_party/tonic/logging/dart_error.h/0
{ "file_path": "engine/third_party/tonic/logging/dart_error.h", "repo_id": "engine", "token_count": 837 }
407
/* * 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_PARAGRAPH_SKIA_H_ #define LIB_TXT_SRC_PARAGRAPH_SKIA_H_ #include <optional> #include "txt/paragraph.h" #include "third_party/skia/modules/skparagraph/include/Paragraph.h" namespace txt { // Implementation of Paragraph based on Skia's text layout module. class ParagraphSkia : public Paragraph { public: ParagraphSkia(std::unique_ptr<skia::textlayout::Paragraph> paragraph, std::vector<flutter::DlPaint>&& dl_paints, bool impeller_enabled); virtual ~ParagraphSkia() = default; double GetMaxWidth() override; double GetHeight() override; double GetLongestLine() override; double GetMinIntrinsicWidth() override; double GetMaxIntrinsicWidth() override; double GetAlphabeticBaseline() override; double GetIdeographicBaseline() override; std::vector<LineMetrics>& GetLineMetrics() override; bool GetLineMetricsAt( int lineNumber, skia::textlayout::LineMetrics* lineMetrics) const override; size_t GetNumberOfLines() const override; int GetLineNumberAt(size_t utf16Offset) const override; bool DidExceedMaxLines() override; void Layout(double width) override; bool Paint(flutter::DisplayListBuilder* builder, double x, double y) override; std::vector<TextBox> GetRectsForRange( size_t start, size_t end, RectHeightStyle rect_height_style, RectWidthStyle rect_width_style) override; std::vector<TextBox> GetRectsForPlaceholders() override; PositionWithAffinity GetGlyphPositionAtCoordinate(double dx, double dy) override; bool GetGlyphInfoAt( unsigned offset, skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const override; bool GetClosestGlyphInfoAtCoordinate( double dx, double dy, skia::textlayout::Paragraph::GlyphInfo* glyphInfo) const override; Range<size_t> GetWordBoundary(size_t offset) override; private: TextStyle SkiaToTxt(const skia::textlayout::TextStyle& skia); std::unique_ptr<skia::textlayout::Paragraph> paragraph_; std::vector<flutter::DlPaint> dl_paints_; std::optional<std::vector<LineMetrics>> line_metrics_; std::vector<TextStyle> line_metrics_styles_; const bool impeller_enabled_; }; } // namespace txt #endif // LIB_TXT_SRC_PARAGRAPH_SKIA_H_
engine/third_party/txt/src/skia/paragraph_skia.h/0
{ "file_path": "engine/third_party/txt/src/skia/paragraph_skia.h", "repo_id": "engine", "token_count": 1018 }
408
/* * Copyright 2017 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_PARAGRAPH_STYLE_H_ #define LIB_TXT_SRC_PARAGRAPH_STYLE_H_ #include <climits> #include <string> #include "font_style.h" #include "font_weight.h" #include "text_style.h" namespace txt { enum class TextAlign { left, right, center, justify, start, end, }; enum class TextDirection { rtl, ltr, }; // Adjusts the leading over and under text. // // kDisableFirstAscent and kDisableLastDescent allow disabling height // adjustments to first line's ascent and the last line's descent. If disabled, // the line will use the default font metric provided ascent/descent and // ParagraphStyle.height or TextStyle.height will not take effect. // // The default behavior is kAll where height adjustments are enabled for all // lines. // // Multiple behaviors can be applied at once with a bitwise | operator. For // example, disabling first ascent and last descent can achieved with: // // (kDisableFirstAscent | kDisableLastDescent). enum TextHeightBehavior { kAll = 0x0, kDisableFirstAscent = 0x1, kDisableLastDescent = 0x2, kDisableAll = 0x1 | 0x2, }; class ParagraphStyle { public: // Default TextStyle. Used in GetTextStyle() to obtain the base TextStyle to // inherit off of. FontWeight font_weight = FontWeight::w400; FontStyle font_style = FontStyle::normal; std::string font_family = ""; double font_size = 14; double height = 1; bool has_height_override = false; size_t text_height_behavior = TextHeightBehavior::kAll; // Strut properties. strut_enabled must be set to true for the rest of the // properties to take effect. // TODO(garyq): Break the strut properties into a separate class. bool strut_enabled = false; FontWeight strut_font_weight = FontWeight::w400; FontStyle strut_font_style = FontStyle::normal; std::vector<std::string> strut_font_families; double strut_font_size = 14; double strut_height = 1; bool strut_has_height_override = false; bool strut_half_leading = false; double strut_leading = -1; // Negative to use font's default leading. [0,inf) // to use custom leading as a ratio of font size. bool force_strut_height = false; // General paragraph properties. TextAlign text_align = TextAlign::start; TextDirection text_direction = TextDirection::ltr; size_t max_lines = std::numeric_limits<size_t>::max(); std::u16string ellipsis; std::string locale; TextStyle GetTextStyle() const; bool unlimited_lines() const; bool ellipsized() const; // Return a text alignment value that is not dependent on the text direction. TextAlign effective_align() const; }; } // namespace txt #endif // LIB_TXT_SRC_PARAGRAPH_STYLE_H_
engine/third_party/txt/src/txt/paragraph_style.h/0
{ "file_path": "engine/third_party/txt/src/txt/paragraph_style.h", "repo_id": "engine", "token_count": 1037 }
409
/* * Copyright 2017 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_TEXT_DECORATION_H_ #define LIB_TXT_SRC_TEXT_DECORATION_H_ namespace txt { // Multiple decorations can be applied at once. Ex: Underline and overline is // (0x1 | 0x2) enum TextDecoration { kNone = 0x0, kUnderline = 0x1, kOverline = 0x2, kLineThrough = 0x4, }; enum TextDecorationStyle { kSolid, kDouble, kDotted, kDashed, kWavy }; } // namespace txt #endif // LIB_TXT_SRC_TEXT_DECORATION_H_
engine/third_party/txt/src/txt/text_decoration.h/0
{ "file_path": "engine/third_party/txt/src/txt/text_decoration.h", "repo_id": "engine", "token_count": 335 }
410
// 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'; class EmbeddedTestFont { const EmbeddedTestFont._({ required this.fontFamily, required this.data, }); static final EmbeddedTestFont flutterTest = EmbeddedTestFont._(fontFamily: 'FlutterTest', data: _flutterTestData); final String fontFamily; final Uint8List data; } final Uint8List _flutterTestData = Uint8List.fromList(<int>[ 0x00, 0x01, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x80, 0x00, 0x03, 0x00, 0x60, 0x42, 0x41, 0x53, 0x45, 0x8a, 0x4b, 0x87, 0x01, 0x00, 0x00, 0x0b, 0x24, 0x00, 0x00, 0x00, 0x82, 0x47, 0x44, 0x45, 0x46, 0x00, 0x29, 0x00, 0x14, 0x00, 0x00, 0x0b, 0x04, 0x00, 0x00, 0x00, 0x1e, 0x4f, 0x53, 0x2f, 0x32, 0x13, 0xfd, 0x90, 0xf2, 0x00, 0x00, 0x01, 0x68, 0x00, 0x00, 0x00, 0x60, 0x63, 0x6d, 0x61, 0x70, 0xec, 0x11, 0x06, 0x0f, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x05, 0x04, 0x63, 0x76, 0x74, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x18, 0x00, 0x00, 0x00, 0x02, 0x67, 0x6c, 0x79, 0x66, 0x09, 0x85, 0x89, 0xf8, 0x00, 0x00, 0x07, 0x3c, 0x00, 0x00, 0x00, 0xd8, 0x68, 0x65, 0x61, 0x64, 0x81, 0x1b, 0xef, 0xfd, 0x00, 0x00, 0x00, 0xec, 0x00, 0x00, 0x00, 0x36, 0x68, 0x68, 0x65, 0x61, 0x07, 0x02, 0x03, 0x0f, 0x00, 0x00, 0x01, 0x24, 0x00, 0x00, 0x00, 0x24, 0x68, 0x6d, 0x74, 0x78, 0x1b, 0x86, 0x00, 0x80, 0x00, 0x00, 0x01, 0xc8, 0x00, 0x00, 0x00, 0x38, 0x6c, 0x6f, 0x63, 0x61, 0x02, 0x7e, 0x02, 0x50, 0x00, 0x00, 0x07, 0x1c, 0x00, 0x00, 0x00, 0x1e, 0x6d, 0x61, 0x78, 0x70, 0x00, 0x52, 0x00, 0x2d, 0x00, 0x00, 0x01, 0x48, 0x00, 0x00, 0x00, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x1a, 0xef, 0x7a, 0x5b, 0x00, 0x00, 0x08, 0x14, 0x00, 0x00, 0x02, 0x25, 0x70, 0x6f, 0x73, 0x74, 0x89, 0x84, 0x28, 0x37, 0x00, 0x00, 0x0a, 0x3c, 0x00, 0x00, 0x00, 0xc7, 0x70, 0x72, 0x65, 0x70, 0x6f, 0x48, 0x68, 0x25, 0x00, 0x00, 0x07, 0x04, 0x00, 0x00, 0x00, 0x11, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xab, 0xb4, 0x91, 0x15, 0x5f, 0x0f, 0x3c, 0xf5, 0x00, 0x1f, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x8e, 0xf4, 0x56, 0x80, 0x00, 0x00, 0x00, 0x00, 0x8e, 0xf4, 0x56, 0x80, 0x00, 0x00, 0xff, 0x00, 0x04, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x03, 0x00, 0xff, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x08, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x02, 0x05, 0x01, 0x90, 0x00, 0x05, 0x00, 0x00, 0x02, 0x99, 0x02, 0xcc, 0x00, 0x00, 0x00, 0x8f, 0x02, 0x99, 0x02, 0xcc, 0x00, 0x00, 0x01, 0xeb, 0x00, 0x33, 0x01, 0x09, 0x00, 0x00, 0x02, 0x00, 0x05, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x20, 0xfe, 0xff, 0x03, 0x00, 0xff, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x01, 0x04, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x55, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x55, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0xcc, 0x00, 0x00, 0x00, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0x00, 0x03, 0x00, 0x01, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x04, 0x03, 0xe2, 0x00, 0x00, 0x00, 0x64, 0x00, 0x40, 0x00, 0x05, 0x00, 0x24, 0x00, 0x7e, 0x00, 0xff, 0x01, 0x31, 0x01, 0x53, 0x01, 0x78, 0x01, 0x92, 0x02, 0xc9, 0x02, 0xdd, 0x03, 0x94, 0x03, 0xa9, 0x03, 0xc0, 0x20, 0x0a, 0x20, 0x26, 0x20, 0x30, 0x20, 0x3a, 0x20, 0x44, 0x21, 0x26, 0x22, 0x06, 0x22, 0x12, 0x22, 0x1e, 0x22, 0x2b, 0x22, 0x48, 0x22, 0x65, 0x22, 0xf2, 0x25, 0xca, 0x30, 0x07, 0x4e, 0x03, 0x4e, 0x09, 0x4e, 0x2d, 0x4e, 0x5d, 0x4e, 0x8c, 0x4e, 0x94, 0x51, 0x6d, 0x53, 0x41, 0x54, 0x26, 0x56, 0xdb, 0x57, 0x1f, 0x65, 0x87, 0x66, 0x2f, 0x67, 0x2c, 0x6b, 0x63, 0x6c, 0x34, 0x6d, 0x4b, 0x70, 0x6b, 0x78, 0x6e, 0x8b, 0xd5, 0x91, 0xd1, 0xf0, 0x02, 0xfe, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x20, 0x00, 0xa1, 0x01, 0x31, 0x01, 0x52, 0x01, 0x78, 0x01, 0x92, 0x02, 0xc6, 0x02, 0xd8, 0x03, 0x94, 0x03, 0xa5, 0x03, 0xbc, 0x20, 0x02, 0x20, 0x13, 0x20, 0x30, 0x20, 0x39, 0x20, 0x44, 0x21, 0x22, 0x22, 0x02, 0x22, 0x0f, 0x22, 0x19, 0x22, 0x2b, 0x22, 0x48, 0x22, 0x60, 0x22, 0xf2, 0x25, 0xca, 0x30, 0x07, 0x4e, 0x00, 0x4e, 0x09, 0x4e, 0x2d, 0x4e, 0x5d, 0x4e, 0x8c, 0x4e, 0x94, 0x51, 0x6b, 0x53, 0x41, 0x54, 0x26, 0x56, 0xd7, 0x57, 0x1f, 0x65, 0x87, 0x66, 0x2f, 0x67, 0x28, 0x6b, 0x63, 0x6c, 0x34, 0x6d, 0x4b, 0x70, 0x6b, 0x78, 0x6e, 0x8b, 0xd5, 0x91, 0xd1, 0xf0, 0x00, 0xfe, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xd2, 0x00, 0x00, 0xfe, 0x8b, 0xfe, 0x71, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdf, 0xd3, 0x00, 0x00, 0xdf, 0xbf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xdd, 0xd8, 0xdd, 0xbb, 0x00, 0x00, 0xdd, 0x11, 0xda, 0x39, 0xcf, 0xfc, 0x00, 0x00, 0xb1, 0xfa, 0xb1, 0xd6, 0xb1, 0xa6, 0xb1, 0x77, 0xb1, 0x6f, 0x00, 0x00, 0xac, 0xc2, 0xab, 0xdd, 0x00, 0x00, 0xa8, 0xe4, 0x9a, 0x7c, 0x99, 0xd4, 0x00, 0x00, 0x94, 0xa0, 0x93, 0xcf, 0x92, 0xb8, 0x8f, 0x98, 0x87, 0x95, 0x74, 0x2e, 0x6e, 0x32, 0x00, 0x00, 0x01, 0x0e, 0x00, 0x01, 0x00, 0x64, 0x01, 0x20, 0x00, 0x00, 0x01, 0xda, 0x00, 0x00, 0x00, 0x00, 0x01, 0xd8, 0x01, 0xde, 0x00, 0x00, 0x01, 0xe6, 0x01, 0xee, 0x01, 0xf6, 0x02, 0x06, 0x00, 0x00, 0x02, 0x2a, 0x00, 0x00, 0x02, 0x2a, 0x02, 0x32, 0x02, 0x3a, 0x02, 0x40, 0x00, 0x00, 0x00, 0x00, 0x02, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x4a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x46, 0x00, 0x00, 0x00, 0x00, 0x02, 0x46, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x04, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x05, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x07, 0x00, 0x00, 0x00, 0x08, 0x00, 0x09, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0b, 0x00, 0x0c, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x01, 0x06, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x06, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03, 0x05, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x00, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x00, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x18, 0xb8, 0x00, 0x00, 0x4c, 0xb8, 0x00, 0xc0, 0x63, 0xb8, 0x00, 0x04, 0x62, 0x20, 0x67, 0x61, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x26, 0x00, 0x26, 0x00, 0x26, 0x00, 0x3c, 0x00, 0x54, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x6c, 0x00, 0x00, 0x00, 0x02, 0x00, 0x80, 0x00, 0x00, 0x03, 0x80, 0x03, 0x00, 0x00, 0x03, 0x00, 0x07, 0x00, 0x22, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x16, 0xe0, 0x12, 0xb2, 0x01, 0x01, 0x01, 0x15, 0x36, 0x16, 0xb0, 0x00, 0x2f, 0xb0, 0x01, 0x2f, 0xb0, 0x02, 0x2f, 0xb0, 0x03, 0x2f, 0xb0, 0x04, 0x2f, 0xb0, 0x07, 0x2f, 0x25, 0x21, 0x11, 0x21, 0x03, 0x11, 0x21, 0x11, 0x01, 0x00, 0x02, 0x00, 0xfe, 0x00, 0x80, 0x03, 0x00, 0x80, 0x02, 0x00, 0xfd, 0x80, 0x03, 0x00, 0xfd, 0x00, 0x00, 0x01, 0x00, 0x00, 0xff, 0x00, 0x04, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x11, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x16, 0xe0, 0x12, 0xb2, 0x01, 0x01, 0x01, 0x15, 0x36, 0x16, 0x00, 0x19, 0x01, 0x21, 0x11, 0x04, 0x00, 0xff, 0x00, 0x04, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0xff, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x16, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x16, 0xe0, 0x12, 0xb2, 0x01, 0x01, 0x01, 0x15, 0x36, 0x16, 0xb0, 0x01, 0x2f, 0xb0, 0x02, 0x2f, 0x19, 0x01, 0x21, 0x11, 0x04, 0x00, 0xff, 0x00, 0x01, 0x00, 0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x16, 0x00, 0xb3, 0x00, 0x00, 0x00, 0x00, 0x16, 0xe0, 0x12, 0xb2, 0x01, 0x01, 0x01, 0x15, 0x36, 0x16, 0xb0, 0x00, 0x2f, 0xb0, 0x03, 0x2f, 0x31, 0x11, 0x21, 0x11, 0x04, 0x00, 0x03, 0x00, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0xae, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1d, 0x00, 0x3c, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x6a, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x07, 0x00, 0x82, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x26, 0x00, 0xd8, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x0b, 0x01, 0x17, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0f, 0x01, 0x43, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x0b, 0x01, 0x6b, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x00, 0x00, 0x3a, 0x00, 0x00, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x01, 0x00, 0x0e, 0x00, 0x5a, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x02, 0x00, 0x0e, 0x00, 0x72, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x03, 0x00, 0x4c, 0x00, 0x8a, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x04, 0x00, 0x16, 0x00, 0xff, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x05, 0x00, 0x1e, 0x01, 0x23, 0x00, 0x03, 0x00, 0x01, 0x04, 0x09, 0x00, 0x06, 0x00, 0x16, 0x01, 0x53, 0x00, 0x43, 0x00, 0x6f, 0x00, 0x70, 0x00, 0x79, 0x00, 0x72, 0x00, 0x69, 0x00, 0x67, 0x00, 0x68, 0x00, 0x74, 0x00, 0x20, 0x00, 0x28, 0x00, 0x63, 0x00, 0x29, 0x00, 0x20, 0x00, 0x31, 0x00, 0x39, 0x00, 0x38, 0x00, 0x30, 0x00, 0x2c, 0x00, 0x20, 0x00, 0x41, 0x00, 0x6e, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x79, 0x00, 0x6d, 0x00, 0x6f, 0x00, 0x75, 0x00, 0x73, 0x00, 0x00, 0x43, 0x6f, 0x70, 0x79, 0x72, 0x69, 0x67, 0x68, 0x74, 0x20, 0x28, 0x63, 0x29, 0x20, 0x31, 0x39, 0x38, 0x30, 0x2c, 0x20, 0x41, 0x6e, 0x6f, 0x6e, 0x79, 0x6d, 0x6f, 0x75, 0x73, 0x00, 0x00, 0x4d, 0x00, 0x69, 0x00, 0x6e, 0x00, 0x67, 0x00, 0x4c, 0x00, 0x69, 0x00, 0x55, 0x00, 0x00, 0x4d, 0x69, 0x6e, 0x67, 0x4c, 0x69, 0x55, 0x00, 0x00, 0x52, 0x00, 0x65, 0x00, 0x67, 0x00, 0x75, 0x00, 0x6c, 0x00, 0x61, 0x00, 0x72, 0x00, 0x00, 0x52, 0x65, 0x67, 0x75, 0x6c, 0x61, 0x72, 0x00, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x74, 0x00, 0x46, 0x00, 0x6f, 0x00, 0x72, 0x00, 0x67, 0x00, 0x65, 0x00, 0x20, 0x00, 0x32, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x20, 0x00, 0x3a, 0x00, 0x20, 0x00, 0x46, 0x00, 0x6c, 0x00, 0x75, 0x00, 0x74, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x20, 0x00, 0x3a, 0x00, 0x20, 0x00, 0x31, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x2d, 0x00, 0x31, 0x00, 0x39, 0x00, 0x38, 0x00, 0x30, 0x00, 0x00, 0x46, 0x6f, 0x6e, 0x74, 0x46, 0x6f, 0x72, 0x67, 0x65, 0x20, 0x32, 0x2e, 0x30, 0x20, 0x3a, 0x20, 0x46, 0x6c, 0x75, 0x74, 0x74, 0x65, 0x72, 0x54, 0x65, 0x73, 0x74, 0x20, 0x3a, 0x20, 0x31, 0x2d, 0x31, 0x2d, 0x31, 0x39, 0x38, 0x30, 0x00, 0x00, 0x46, 0x00, 0x6c, 0x00, 0x75, 0x00, 0x74, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x00, 0x46, 0x6c, 0x75, 0x74, 0x74, 0x65, 0x72, 0x54, 0x65, 0x73, 0x74, 0x00, 0x00, 0x56, 0x00, 0x65, 0x00, 0x72, 0x00, 0x73, 0x00, 0x69, 0x00, 0x6f, 0x00, 0x6e, 0x00, 0x20, 0x00, 0x30, 0x00, 0x30, 0x00, 0x31, 0x00, 0x2e, 0x00, 0x30, 0x00, 0x30, 0x00, 0x30, 0x00, 0x00, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x20, 0x30, 0x30, 0x31, 0x2e, 0x30, 0x30, 0x30, 0x00, 0x00, 0x46, 0x00, 0x6c, 0x00, 0x75, 0x00, 0x74, 0x00, 0x74, 0x00, 0x65, 0x00, 0x72, 0x00, 0x54, 0x00, 0x65, 0x00, 0x73, 0x00, 0x74, 0x00, 0x00, 0x46, 0x6c, 0x75, 0x74, 0x74, 0x65, 0x72, 0x54, 0x65, 0x73, 0x74, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x7e, 0x00, 0x13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x01, 0x02, 0x01, 0x03, 0x01, 0x04, 0x01, 0x05, 0x01, 0x06, 0x01, 0x07, 0x01, 0x08, 0x01, 0x09, 0x01, 0x0a, 0x01, 0x0b, 0x01, 0x0c, 0x06, 0x53, 0x71, 0x75, 0x61, 0x72, 0x65, 0x0e, 0x41, 0x73, 0x63, 0x65, 0x6e, 0x74, 0x20, 0x46, 0x6c, 0x75, 0x73, 0x68, 0x65, 0x64, 0x0f, 0x44, 0x65, 0x73, 0x63, 0x65, 0x6e, 0x74, 0x20, 0x46, 0x6c, 0x75, 0x73, 0x68, 0x65, 0x64, 0x0c, 0x46, 0x75, 0x6c, 0x6c, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0b, 0x31, 0x2f, 0x32, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0b, 0x31, 0x2f, 0x33, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0b, 0x31, 0x2f, 0x34, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0b, 0x31, 0x2f, 0x36, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0b, 0x31, 0x2f, 0x35, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0c, 0x31, 0x2f, 0x31, 0x30, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x0c, 0x5a, 0x65, 0x72, 0x6f, 0x20, 0x41, 0x64, 0x76, 0x61, 0x6e, 0x63, 0x65, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0d, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x12, 0x00, 0x03, 0x68, 0x61, 0x6e, 0x67, 0x69, 0x64, 0x65, 0x6f, 0x72, 0x6f, 0x6d, 0x6e, 0x00, 0x03, 0x67, 0x72, 0x65, 0x6b, 0x00, 0x14, 0x68, 0x61, 0x6e, 0x69, 0x00, 0x30, 0x6c, 0x61, 0x74, 0x6e, 0x00, 0x4c, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x0e, 0x00, 0x12, 0x00, 0x01, 0x03, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x0e, 0x00, 0x12, 0x00, 0x01, 0x03, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x03, 0x00, 0x0a, 0x00, 0x0e, 0x00, 0x12, 0x00, 0x01, 0x03, 0x00, 0x00, 0x01, 0xff, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, ]);
engine/third_party/web_test_fonts/lib/web_test_fonts/web_test_fonts.dart/0
{ "file_path": "engine/third_party/web_test_fonts/lib/web_test_fonts/web_test_fonts.dart", "repo_id": "engine", "token_count": 13333 }
411
// 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'; import 'package:args/args.dart'; import 'package:path/path.dart' as path; import 'package:process/process.dart'; const LocalProcessManager processManager = LocalProcessManager(); /// Runs the Android SDK Lint tool on flutter/shell/platform/android. /// /// This script scans the flutter/shell/platform/android directory for Java /// files to build a `project.xml` file. This file is then passed to the lint /// tool. If an `--html` flag is also passed in, HTML output is reqeusted in the /// directory for the optional `--out` parameter, which defaults to /// `lint_report`. Otherwise the output is printed to STDOUT. /// /// The `--in` parameter may be specified to force this script to scan a /// specific location for the engine repository, and expects to be given the /// `src` directory that contains both `third_party` and `flutter`. /// /// At the time of this writing, the Android Lint tool doesn't work well with /// Java > 1.8. This script will print a warning if you are not running /// Java 1.8. Future<void> main(List<String> args) async { final ArgParser argParser = setupOptions(); final int exitCode = await runLint(argParser, argParser.parse(args)); exit(exitCode); } Future<int> runLint(ArgParser argParser, ArgResults argResults) async { final String inArgument = argResults['in'] as String; final Directory androidDir = Directory(path.join( inArgument, 'flutter', 'shell', 'platform', 'android', )); if (!androidDir.existsSync()) { print('This command must be run from the engine/src directory, ' 'or be passed that directory as the --in parameter.\n'); print(argParser.usage); return -1; } final Directory androidSdkDir = Directory( path.join(inArgument, 'third_party', 'android_tools', 'sdk'), ); if (!androidSdkDir.existsSync()) { print('The Android SDK for this engine is missing from the ' 'third_party/android_tools directory. Have you run gclient sync?\n'); print(argParser.usage); return -1; } final bool rebaseline = argResults['rebaseline'] as bool; if (rebaseline) { print('Removing previous baseline.xml...'); final File baselineXml = File(baselineXmlPath); if (baselineXml.existsSync()) { await baselineXml.delete(); } } print('Preparing project.xml...'); final IOSink projectXml = File(projectXmlPath).openWrite(); projectXml.write(''' <!-- THIS FILE IS GENERATED. PLEASE USE THE INCLUDED DART PROGRAM WHICH --> <!-- WILL AUTOMATICALLY FIND ALL .java FILES AND INCLUDE THEM HERE --> <project> <sdk dir="${androidSdkDir.path}" /> <module name="FlutterEngine" android="true" library="true" compile-sdk-version="android-U"> <manifest file="${path.join(androidDir.path, 'AndroidManifest.xml')}" /> '''); for (final FileSystemEntity entity in androidDir.listSync(recursive: true)) { if (!entity.path.endsWith('.java')) { continue; } if (entity.path.endsWith('Test.java')) { continue; } projectXml.writeln(' <src file="${entity.path}" />'); } projectXml.write(''' </module> </project> '''); await projectXml.close(); print('Wrote project.xml, starting lint...'); final List<String> lintArgs = <String>[ path.join(androidSdkDir.path, 'cmdline-tools', 'latest', 'bin', 'lint'), '--project', projectXmlPath, '--compile-sdk-version', '34', '--showall', '--exitcode', // Set non-zero exit code on errors '-Wall', '-Werror', '--baseline', baselineXmlPath, ]; final bool html = argResults['html'] as bool; if (html) { lintArgs.addAll(<String>['--html', argResults['out'] as String]); } final String javahome = getJavaHome(inArgument); print('Using JAVA_HOME=$javahome'); final Process lintProcess = await processManager.start( lintArgs, environment: <String, String>{ 'JAVA_HOME': javahome, }, ); lintProcess.stdout.pipe(stdout); lintProcess.stderr.pipe(stderr); return lintProcess.exitCode; } /// Prepares an [ArgParser] for this script. ArgParser setupOptions() { final ArgParser argParser = ArgParser(); argParser ..addOption( 'in', help: 'The path to `engine/src`.', defaultsTo: path.relative( path.join( projectDir, '..', '..', '..', ), ), ) ..addFlag( 'help', help: 'Print usage of the command.', negatable: false, ) ..addFlag( 'rebaseline', help: 'Recalculates the baseline for errors and warnings ' 'in this project.', negatable: false, ) ..addFlag( 'html', help: 'Creates an HTML output for this report instead of printing ' 'command line output.', negatable: false, ) ..addOption( 'out', help: 'The path to write the generated HTML report. Ignored if ' '--html is not also true.', defaultsTo: path.join(projectDir, 'lint_report'), ); return argParser; } String getJavaHome(String src) { if (Platform.isMacOS) { return path.normalize('$src/third_party/java/openjdk/Contents/Home/'); } return path.normalize('$src/third_party/java/openjdk/'); } /// The root directory of this project. String get projectDir => path.dirname( path.dirname( path.fromUri(Platform.script), ), ); /// The path to use for project.xml, which tells the linter where to find source /// files. String get projectXmlPath => path.join(projectDir, 'project.xml'); /// The path to use for baseline.xml, which tells the linter what errors or /// warnings to ignore. String get baselineXmlPath => path.join(projectDir, 'baseline.xml');
engine/tools/android_lint/bin/main.dart/0
{ "file_path": "engine/tools/android_lint/bin/main.dart", "repo_id": "engine", "token_count": 2103 }
412
// 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, File, Platform, stderr; import 'package:clang_tidy/clang_tidy.dart'; import 'package:clang_tidy/src/command.dart'; import 'package:clang_tidy/src/lint_target.dart'; import 'package:clang_tidy/src/options.dart'; import 'package:engine_repo_tools/engine_repo_tools.dart'; import 'package:litetest/litetest.dart'; import 'package:path/path.dart' as path; import 'package:process/process.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; /// A test fixture for the `clang-tidy` tool. final class Fixture { /// Simulates running the tool with the given [args]. factory Fixture.fromCommandLine(List<String> args, { ProcessManager? processManager, Engine? engine, }) { processManager ??= FakeProcessManager(); final StringBuffer outBuffer = StringBuffer(); final StringBuffer errBuffer = StringBuffer(); return Fixture._(ClangTidy.fromCommandLine( args, outSink: outBuffer, errSink: errBuffer, processManager: processManager, engine: engine, ), errBuffer); } /// Simulates running the tool with the given [options]. factory Fixture.fromOptions(Options options, { ProcessManager? processManager, }) { processManager ??= FakeProcessManager(); final StringBuffer outBuffer = StringBuffer(); final StringBuffer errBuffer = StringBuffer(); return Fixture._(ClangTidy( buildCommandsPath: options.buildCommandsPath, lintTarget: options.lintTarget, fix: options.fix, outSink: outBuffer, errSink: errBuffer, processManager: processManager, ), errBuffer); } Fixture._( this.tool, this.errBuffer, ); /// The `clang-tidy` tool. final ClangTidy tool; /// Captured `stderr` from the tool. final StringBuffer errBuffer; } // Recorded locally from clang-tidy. const String _tidyOutput = ''' /runtime.dart_isolate.o" in /Users/aaclarke/dev/engine/src/out/host_debug exited with code 1 3467 warnings generated. /Users/aaclarke/dev/engine/src/flutter/runtime/dart_isolate.cc:167:32: error: std::move of the const variable 'dart_entrypoint_args' has no effect; remove std::move() or make the variable non-const [performance-move-const-arg,-warnings-as-errors] std::move(dart_entrypoint_args))) { ^~~~~~~~~~ ~ Suppressed 3474 warnings (3466 in non-user code, 8 NOLINT). Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well. 1 warning treated as error : 3467 warnings generated. Suppressed 3474 warnings (3466 in non-user code, 8 NOLINT). Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well. 1 warning treated as error '''; const String _tidyTrimmedOutput = ''' /Users/aaclarke/dev/engine/src/flutter/runtime/dart_isolate.cc:167:32: error: std::move of the const variable 'dart_entrypoint_args' has no effect; remove std::move() or make the variable non-const [performance-move-const-arg,-warnings-as-errors] std::move(dart_entrypoint_args))) { ^~~~~~~~~~ ~ Suppressed 3474 warnings (3466 in non-user code, 8 NOLINT). Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well. 1 warning treated as error'''; void _withTempFile(String prefix, void Function(String path) func) { final String filePath = path.join(io.Directory.systemTemp.path, '$prefix-temp-file'); final io.File file = io.File(filePath); file.createSync(); try { func(file.path); } finally { file.deleteSync(); } } Future<int> main(List<String> args) async { final String? buildCommands = args.firstOrNull ?? Engine.findWithin().latestOutput()?.compileCommandsJson.path; if (buildCommands == null || args.length > 1) { io.stderr.writeln( 'Usage: clang_tidy_test.dart [path/to/compile_commands.json]', ); return 1; } test('--help gives help, and uses host_debug by default outside of an engine root', () async { final io.Directory rootDir = io.Directory.systemTemp.createTempSync('clang_tidy_test'); try { final Fixture fixture = Fixture.fromCommandLine( <String>['--help'], engine: TestEngine.createTemp(rootDir: rootDir) ); final int result = await fixture.tool.run(); expect(fixture.tool.options.help, isTrue); expect(result, equals(0)); final String errors = fixture.errBuffer.toString(); expect(errors, contains('Usage: ')); expect(errors, contains('defaults to "host_debug"')); } finally { rootDir.deleteSync(recursive: true); } }); test('--help gives help, and uses the latest build by default outside in an engine root', () async { final io.Directory rootDir = io.Directory.systemTemp.createTempSync('clang_tidy_test'); final io.Directory buildDir = io.Directory(path.join(rootDir.path, 'out', 'host_debug_unopt_arm64'))..createSync(recursive: true); try { final Fixture fixture = Fixture.fromCommandLine( <String>['--help'], engine: TestEngine.createTemp(rootDir: rootDir, outputs: <TestOutput>[ TestOutput(buildDir), ]) ); final int result = await fixture.tool.run(); expect(fixture.tool.options.help, isTrue); expect(result, equals(0)); final String errors = fixture.errBuffer.toString(); expect(errors, contains('Usage: ')); expect(errors, contains('defaults to "host_debug_unopt_arm64"')); } finally { rootDir.deleteSync(recursive: true); } }); test('trimmed clang-tidy output', () { expect(_tidyTrimmedOutput, equals(ClangTidy.trimOutput(_tidyOutput))); }); test('Error when --compile-commands and --target-variant are used together', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--compile-commands', '/unused', '--target-variant', 'unused' ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString(), contains( 'ERROR: --compile-commands option cannot be used with --target-variant.', )); }); test('Error when --compile-commands and --src-dir are used together', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--compile-commands', '/unused', '--src-dir', '/unused', ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString(), contains( 'ERROR: --compile-commands option cannot be used with --src-dir.', )); }); test('shard-id valid', () async { _withTempFile('shard-id-valid', (String path) { final Options options = Options.fromCommandLine( <String>[ '--compile-commands=$path', '--shard-variants=variant', '--shard-id=1', ],); expect(options.errorMessage, isNull); expect(options.shardId, equals(1)); }); }); test('clang-tidy specified', () async { _withTempFile('shard-id-valid', (String path) { final Options options = Options.fromCommandLine( <String>[ '--clang-tidy=foo/bar', ],); expect(options.clangTidyPath, isNotNull); expect(options.clangTidyPath!.path, equals('foo/bar')); }); }); test('clang-tidy unspecified', () async { _withTempFile('shard-id-valid', (String path) { final Options options = Options.fromCommandLine( <String>[],); expect(options.clangTidyPath, isNull); }); }); test('shard-id invalid', () async { _withTempFile('shard-id-valid', (String path) { final StringBuffer errBuffer = StringBuffer(); final Options options = Options.fromCommandLine(<String>[ '--compile-commands=$path', '--shard-variants=variant', '--shard-id=2', ], errSink: errBuffer); expect(options.errorMessage, isNotNull); expect(options.shardId, isNull); expect(options.errorMessage, contains('Invalid shard-id value')); }); }); test('Error when --compile-commands path does not exist', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--compile-commands', '/does/not/exist', ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString().split('\n')[0], hasMatch( r"ERROR: Build commands path .*/does/not/exist doesn't exist.", )); }); test('Error when --src-dir path does not exist, uses target variant in path', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--src-dir', '/does/not/exist', '--target-variant', 'ios_debug_unopt', ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString().split('\n')[0], hasMatch( r'ERROR: Build commands path .*/does/not/exist' r'[/\\]out[/\\]ios_debug_unopt[/\\]compile_commands.json' r" doesn't exist.", )); }); test('Error when --lint-all and --lint-head are used together', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--compile-commands', '/unused', '--lint-all', '--lint-head', ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString(), contains( 'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.', )); }); test('Error when --lint-all and --lint-regex are used together', () async { final Fixture fixture = Fixture.fromCommandLine( <String>[ '--compile-commands', '/unused', '--lint-all', '--lint-regex=".*"', ], ); final int result = await fixture.tool.run(); expect(result, equals(1)); expect(fixture.errBuffer.toString(), contains( 'ERROR: At most one of --lint-all, --lint-head, --lint-regex can be passed.', )); }); test('lintAll=true checks all files', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), lintTarget: const LintAll(), ), ); final List<io.File> fileList = await fixture.tool.computeFilesOfInterest(); expect(fileList.length, greaterThan(1000)); }); test('lintAll=false does not check all files', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), // Intentional: // ignore: avoid_redundant_argument_values lintTarget: const LintChanged(), ), processManager: FakeProcessManager( onStart: (List<String> command) { if (command.first == 'git') { // This just allows git to not actually be called. return FakeProcess(); } return FakeProcessManager.unhandledStart(command); }, ), ); final List<io.File> fileList = await fixture.tool.computeFilesOfInterest(); expect(fileList.length, lessThan(300)); }); test('lintAll=pattern checks based on a RegEx', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), lintTarget: const LintRegex(r'.*test.*\.cc$'), ), processManager: FakeProcessManager( onStart: (List<String> command) { if (command.first == 'git') { // This just allows git to not actually be called. return FakeProcess(); } return FakeProcessManager.unhandledStart(command); }, ), ); final List<io.File> fileList = await fixture.tool.computeFilesOfInterest(); expect(fileList.length, lessThan(2000)); }); test('Sharding', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), lintTarget: const LintAll(), ), processManager: FakeProcessManager( onStart: (List<String> command) { if (command.first == 'git') { // This just allows git to not actually be called. return FakeProcess(); } return FakeProcessManager.unhandledStart(command); }, ), ); Map<String, String> makeBuildCommandEntry(String filePath) { return <String, String>{ 'directory': '/unused', 'command': '../../buildtools/mac-x64/clang/bin/clang $filePath', 'file': filePath, }; } final List<String> filePaths = <String>[ for (int i = 0; i < 10; ++i) '/path/to/a/source_file_$i.cc' ]; final List<Map<String, String>> buildCommandsData = filePaths.map((String e) => makeBuildCommandEntry(e)).toList(); final List<Map<String, String>> shardBuildCommandsData = filePaths.sublist(6).map((String e) => makeBuildCommandEntry(e)).toList(); { final List<Command> commands = await fixture.tool.getLintCommandsForFiles( buildCommandsData, filePaths.map((String e) => io.File(e)).toList(), <List<dynamic>>[shardBuildCommandsData], 0, ); final Iterable<String> commandFilePaths = commands.map((Command e) => e.filePath); expect(commands.length, equals(8)); expect(commandFilePaths.contains('/path/to/a/source_file_0.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_1.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_2.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_3.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_4.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_5.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_6.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_7.cc'), false); expect(commandFilePaths.contains('/path/to/a/source_file_8.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_9.cc'), false); } { final List<Command> commands = await fixture.tool.getLintCommandsForFiles( buildCommandsData, filePaths.map((String e) => io.File(e)).toList(), <List<Map<String, String>>>[shardBuildCommandsData], 1, ); final Iterable<String> commandFilePaths = commands.map((Command e) => e.filePath); expect(commands.length, equals(8)); expect(commandFilePaths.contains('/path/to/a/source_file_0.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_1.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_2.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_3.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_4.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_5.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_6.cc'), false); expect(commandFilePaths.contains('/path/to/a/source_file_7.cc'), true); expect(commandFilePaths.contains('/path/to/a/source_file_8.cc'), false); expect(commandFilePaths.contains('/path/to/a/source_file_9.cc'), true); } }); test('No Commands are produced when no files changed', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), lintTarget: const LintAll(), ), ); const String filePath = '/path/to/a/source_file.cc'; final List<dynamic> buildCommandsData = <Map<String, dynamic>>[ <String, dynamic>{ 'directory': '/unused', 'command': '../../buildtools/mac-x64/clang/bin/clang $filePath', 'file': filePath, }, ]; final List<Command> commands = await fixture.tool.getLintCommandsForFiles( buildCommandsData, <io.File>[], <List<dynamic>>[], null, ); expect(commands, isEmpty); }); test('A Command is produced when a file is changed', () async { final Fixture fixture = Fixture.fromOptions( Options( buildCommandsPath: io.File(buildCommands), lintTarget: const LintAll(), ), ); // This file needs to exist, and be UTF8 line-parsable. final String filePath = io.Platform.script.toFilePath(); final List<dynamic> buildCommandsData = <Map<String, dynamic>>[ <String, dynamic>{ 'directory': '/unused', 'command': '../../buildtools/mac-x64/clang/bin/clang $filePath', 'file': filePath, }, ]; final List<Command> commands = await fixture.tool.getLintCommandsForFiles( buildCommandsData, <io.File>[io.File(filePath)], <List<dynamic>>[], null, ); expect(commands, isNotEmpty); final Command command = commands.first; expect(command.tidyPath, contains('clang/bin/clang-tidy')); final Options noFixOptions = Options(buildCommandsPath: io.File('.')); expect(noFixOptions.fix, isFalse); final WorkerJob jobNoFix = command.createLintJob(noFixOptions); expect(jobNoFix.command[0], endsWith('../../buildtools/mac-x64/clang/bin/clang-tidy')); expect(jobNoFix.command[1], endsWith(filePath.replaceAll('/', io.Platform.pathSeparator))); expect(jobNoFix.command[2], '--warnings-as-errors=*'); expect(jobNoFix.command[3], '--'); expect(jobNoFix.command[4], ''); expect(jobNoFix.command[5], endsWith(filePath)); final Options fixOptions = Options(buildCommandsPath: io.File('.'), fix: true); final WorkerJob jobWithFix = command.createLintJob(fixOptions); expect(jobWithFix.command[0], endsWith('../../buildtools/mac-x64/clang/bin/clang-tidy')); expect(jobWithFix.command[1], endsWith(filePath.replaceAll('/', io.Platform.pathSeparator))); expect(jobWithFix.command[2], '--warnings-as-errors=*'); expect(jobWithFix.command[3], '--fix'); expect(jobWithFix.command[4], '--format-style=file'); expect(jobWithFix.command[5], '--'); expect(jobWithFix.command[6], ''); expect(jobWithFix.command[7], endsWith(filePath)); }); test('Command getLintAction flags third_party files', () async { final LintAction lintAction = await Command.getLintAction( '/some/file/in/a/third_party/dependency', ); expect(lintAction, equals(LintAction.skipThirdParty)); }); test('Command getLintAction flags missing files', () async { final LintAction lintAction = await Command.getLintAction( '/does/not/exist', ); expect(lintAction, equals(LintAction.skipMissing)); }); test('Command getLintActionFromContents flags FLUTTER_NOLINT', () async { final LintAction lintAction = await Command.lintActionFromContents( Stream<String>.fromIterable(<String>[ '// Copyright 2013 The Flutter Authors. All rights reserved.\n', '// Use of this source code is governed by a BSD-style license that can be\n', '// found in the LICENSE file.\n', '\n', '// FLUTTER_NOLINT: https://github.com/flutter/flutter/issues/68332\n', '\n', '#include "flutter/shell/version/version.h"\n', ]), ); expect(lintAction, equals(LintAction.skipNoLint)); }); test('Command getLintActionFromContents flags malformed FLUTTER_NOLINT', () async { final LintAction lintAction = await Command.lintActionFromContents( Stream<String>.fromIterable(<String>[ '// Copyright 2013 The Flutter Authors. All rights reserved.\n', '// Use of this source code is governed by a BSD-style license that can be\n', '// found in the LICENSE file.\n', '\n', '// FLUTTER_NOLINT: https://gir/flutter/issues/68332\n', '\n', '#include "flutter/shell/version/version.h"\n', ]), ); expect(lintAction, equals(LintAction.failMalformedNoLint)); }); test('Command getLintActionFromContents flags that we should lint', () async { final LintAction lintAction = await Command.lintActionFromContents( Stream<String>.fromIterable(<String>[ '// Copyright 2013 The Flutter Authors. All rights reserved.\n', '// Use of this source code is governed by a BSD-style license that can be\n', '// found in the LICENSE file.\n', '\n', '#include "flutter/shell/version/version.h"\n', ]), ); expect(lintAction, equals(LintAction.lint)); }); test('Command filters out sed command after a compile command', () { final Command command = Command.fromMap(<String, String>{ 'directory': '/unused', 'command': '../../buildtools/mac-x64/clang/bin/clang filename ' "&& sed -i 's@/b/f/w@../..@g' filename", 'file': 'unused', }); expect(command.tidyArgs.trim(), 'filename'); }); test('Command filters out the -MF flag', () { final Command command = Command.fromMap(<String, String>{ 'directory': '/unused', 'command': '../../buildtools/mac-x64/clang/bin/clang -MF stuff filename ', 'file': 'unused', }); expect(command.tidyArgs.trim(), 'filename'); }); test('Command filters out rewrapper command before a compile command', () { final Command command = Command.fromMap(<String, String>{ 'directory': '/unused', 'command': 'flutter/engine/src/buildtools/mac-arm64/reclient/rewrapper ' '--cfg=flutter/engine/src/flutter/build/rbe/rewrapper-mac-arm64.cfg ' '--exec_root=flutter/engine/src/ ' '--labels=type=compile,compiler=clang,lang=cpp ' '../../buildtools/mac-x64/clang/bin/clang++ filename ', 'file': 'unused', }); expect(command.tidyArgs.trim(), 'filename'); }); return 0; }
engine/tools/clang_tidy/test/clang_tidy_test.dart/0
{ "file_path": "engine/tools/clang_tidy/test/clang_tidy_test.dart", "repo_id": "engine", "token_count": 8839 }
413
# Generated by pub on 2020-01-15 10:08:29.776333. const_finder_fixtures:lib/ const_finder_fixtures_package:pkg/
engine/tools/const_finder/test/fixtures/.packages/0
{ "file_path": "engine/tools/const_finder/test/fixtures/.packages", "repo_id": "engine", "token_count": 42 }
414
// 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:engine_build_configs/engine_build_configs.dart'; import 'command.dart'; import 'flags.dart'; // ignore: public_member_api_docs final class QueryCommand extends CommandBase { // ignore: public_member_api_docs QueryCommand({ required super.environment, required this.configs, }) { // Add options here that are common to all queries. argParser ..addFlag( allFlag, abbr: 'a', help: 'List all results, even when not relevant on this platform', negatable: false, ) ..addOption( builderFlag, abbr: 'b', help: 'Restrict the query to a single builder.', allowed: <String>[ for (final MapEntry<String, BuilderConfig> entry in configs.entries) if (entry.value.canRunOn(environment.platform)) entry.key, ], allowedHelp: <String, String>{ // TODO(zanderso): Add human readable descriptions to the json files. for (final MapEntry<String, BuilderConfig> entry in configs.entries) if (entry.value.canRunOn(environment.platform)) entry.key: entry.value.path, }, ); addSubcommand(QueryBuildersCommand( environment: environment, configs: configs, )); } /// Build configurations loaded from the engine from under ci/builders. final Map<String, BuilderConfig> configs; @override String get name => 'query'; @override String get description => 'Provides information about build configurations ' 'and tests.'; } /// The 'query builds' command. final class QueryBuildersCommand extends CommandBase { /// Constructs the 'query build' command. QueryBuildersCommand({ required super.environment, required this.configs, }); /// Build configurations loaded from the engine from under ci/builders. final Map<String, BuilderConfig> configs; @override String get name => 'builders'; @override String get description => 'Provides information about CI builder ' 'configurations'; @override Future<int> run() async { // Loop through all configs, and log those that are compatible with the // current platform. final bool all = parent!.argResults![allFlag]! as bool; final String? builderName = parent!.argResults![builderFlag] as String?; final bool verbose = globalResults![verboseFlag]! as bool; if (!verbose) { environment.logger.status( 'Add --verbose to see detailed information about each builder', ); environment.logger.status(''); } for (final String key in configs.keys) { if (builderName != null && key != builderName) { continue; } final BuilderConfig config = configs[key]!; if (!config.canRunOn(environment.platform) && !all) { continue; } environment.logger.status('"$key" builder:'); for (final Build build in config.builds) { if (!build.canRunOn(environment.platform) && !all) { continue; } environment.logger.status('"${build.name}" config', indent: 3); if (!verbose) { continue; } environment.logger.status('gn flags:', indent: 6); for (final String flag in build.gn) { environment.logger.status(flag, indent: 9); } if (build.ninja.targets.isNotEmpty) { environment.logger.status('ninja targets:', indent: 6); for (final String target in build.ninja.targets) { environment.logger.status(target, indent: 9); } } } } return 0; } }
engine/tools/engine_tool/lib/src/commands/query_command.dart/0
{ "file_path": "engine/tools/engine_tool/lib/src/commands/query_command.dart", "repo_id": "engine", "token_count": 1422 }
415
// 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' as convert; import 'dart:ffi' as ffi show Abi; 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:engine_tool/src/commands/command_runner.dart'; import 'package:engine_tool/src/environment.dart'; import 'package:engine_tool/src/logger.dart'; import 'package:litetest/litetest.dart'; import 'package:platform/platform.dart'; import 'package:process_fakes/process_fakes.dart'; import 'package:process_runner/process_runner.dart'; import 'fixtures.dart' as fixtures; void main() { final Engine engine; try { engine = Engine.findWithin(); } catch (e) { io.stderr.writeln(e); io.exitCode = 1; return; } final BuilderConfig linuxTestConfig = BuilderConfig.fromJson( path: 'ci/builders/linux_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Linux')) as Map<String, Object?>, ); final BuilderConfig macTestConfig = BuilderConfig.fromJson( path: 'ci/builders/mac_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Mac-12')) as Map<String, Object?>, ); final BuilderConfig winTestConfig = BuilderConfig.fromJson( path: 'ci/builders/win_test_config.json', map: convert.jsonDecode(fixtures.testConfig('Windows-11')) as Map<String, Object?>, ); final Map<String, BuilderConfig> configs = <String, BuilderConfig>{ 'linux_test_config': linuxTestConfig, 'linux_test_config2': linuxTestConfig, 'mac_test_config': macTestConfig, 'win_test_config': winTestConfig, }; (Environment, List<List<String>>) macEnv(Logger logger) { final List<List<String>> runHistory = <List<String>>[]; return ( Environment( abi: ffi.Abi.macosArm64, engine: engine, platform: FakePlatform( operatingSystem: Platform.macOS, resolvedExecutable: io.Platform.resolvedExecutable), processRunner: ProcessRunner( processManager: FakeProcessManager(onStart: (List<String> command) { runHistory.add(command); return FakeProcess(); }, onRun: (List<String> command) { // Should not be executed. assert(false); return io.ProcessResult(81, 1, '', ''); })), logger: logger, ), runHistory ); } test('invoked linters', () async { final Logger logger = Logger.test(); final (Environment env, List<List<String>> runHistory) = macEnv(logger); final ToolCommandRunner runner = ToolCommandRunner( environment: env, configs: configs, ); final int result = await runner.run(<String>['lint']); expect(result, equals(0)); expect(runHistory.length, greaterThanOrEqualTo(4)); expect(runHistory[0].firstOrNull, contains('analyze.sh')); }); }
engine/tools/engine_tool/test/lint_command_test.dart/0
{ "file_path": "engine/tools/engine_tool/test/lint_command_test.dart", "repo_id": "engine", "token_count": 1155 }
416
# 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/dart/config.gni") import("//flutter/tools/fuchsia/dart/dart.gni") import("//flutter/tools/fuchsia/flutter/internal/flutter_dart_component.gni") # Defines a Dart component which can be used in a fuchsia package # # Dart components require at least one library which contains a main # entry point. The library should be defined using the dart_library.gni. # # ``` # dart_library("lib") { # package_name = "my_library" # sources = [ "main.dart" ] # } # ``` # # Once a library is defined a dart component can be created which # depends on this package. If the component needs any other resources they may # be defined using the resource target and added to the components deps. # # ``` # resource("text-file") { # sources = [ "text_file.txt" ] # outputs = [ "data/text_file.txt" ] # } # # dart_component("my-component") { # manifest = "meta/my-component.cmx" # main_package = "my_library" # deps = [ # ":lib", # ":text-file", # ] # } # ``` # # Once a component is defined it can be added as a dep of a fuchsia_package # ``` # fuchsia_package("my-package") { # deps = [ # ":my-component", # ] # } # ``` # # Parameters # # manifest (required) # The component manifest # Type: path # # main_package (optional) # The name of the package containing main_dart # Type: string # Default: component_name with dashes replaced by underscores, if defined. # Otherwise, the target_name with dashes replaced by underscores will be # used. # # component_name (optional) # The name of the component. # Type: string # Default: target_name # # main_dart (optional) # File containing the main function of the component. # Type: string # Default: main.dart # # package_root (optional) # The root of the package generated for this component. Each component must # have a unique package_root. For each component, there must be a # pubspec.yaml and an analysis_options.yaml at the package root. # Type: path # Default: "." # # build_cfg (optional) # Specifies the parameters for building the component. # See //build/dart/dart_build_config.gni for predefined configs. # # deps # testonly # visibility template("dart_component") { assert(defined(invoker.manifest), "Must define manifest") if (defined(invoker.build_cfg)) { _build_cfg = invoker.build_cfg } else { _build_cfg = dart_default_build_cfg } _component_deps = [] if (defined(invoker.deps)) { _component_deps += invoker.deps } if (defined(invoker.main_dart)) { _main_dart = invoker.main_dart } else { _main_dart = "main.dart" } if (defined(invoker.main_package)) { _main_package = invoker.main_package } else if (defined(invoker.component_name)) { _main_package = string_replace(invoker.component_name, "-", "_") } else { _main_package = string_replace(target_name, "-", "_") } flutter_dart_component(target_name) { forward_variables_from(invoker, "*", [ "main_package", "build_cfg", "deps", "main_dart", ]) main_package = _main_package deps = _component_deps main_dart = _main_dart build_cfg = _build_cfg } }
engine/tools/fuchsia/dart/dart_component.gni/0
{ "file_path": "engine/tools/fuchsia/dart/dart_component.gni", "repo_id": "engine", "token_count": 1430 }
417
#!/bin/bash # 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. # ### Builds and copies the Flutter and Dart runners for the Fuchsia platform. ### ### Arguments: ### --runtime-mode: The runtime mode to build Flutter in. ### Valid values: [debug, profile, release] ### Default value: debug ### --fuchsia-cpu: The architecture of the Fuchsia device to target. ### Valid values: [x64, arm64] ### Default value: x64 ### --unoptimized: Disables C++ compiler optimizations. ### --goma: Speeds up builds for Googlers. sorry. :( ### ### Any additional arguments are forwarded directly to GN. set -e # Fail on any error. source "$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"/lib/vars.sh || exit $? ensure_fuchsia_dir ensure_engine_dir ensure_ninja # Parse arguments. runtime_mode="debug" compilation_mode="jit" fuchsia_cpu="x64" goma=0 goma_flags="" ninja_cmd="ninja" unoptimized_flags="" unoptimized_suffix="" extra_gn_args=() while [[ $# -gt 0 ]]; do case $1 in --runtime-mode) shift # past argument runtime_mode="$1" shift # past value if [[ "${runtime_mode}" == debug ]] then compilation_mode="jit" elif [[ "${runtime_mode}" == profile || "${runtime_mode}" == release ]] then compilation_mode="aot" else engine-error "Invalid value for --runtime_mode: ${runtime_mode}" exit 1 fi ;; --fuchsia-cpu) shift # past argument fuchsia_cpu="$1" shift # past value if [[ "${fuchsia_cpu}" != x64 && "${fuchsia_cpu}" != arm64 ]] then engine-error "Invalid value for --fuchsia-cpu: ${fuchsia_cpu}" exit 1 fi ;; --goma) goma=1 goma_flags="--goma" ninja_cmd="autoninja" shift # past argument ;; --unopt|--unoptimized) unoptimized_flags="--unoptimized" unoptimized_suffix="_unopt" shift # past argument ;; *) extra_gn_args+=("$1") # forward argument shift # past argument ;; esac done fuchsia_flutter_git_revision="$(cat $FUCHSIA_DIR/integration/jiri.lock | grep -A 1 "\"package\": \"flutter/fuchsia\"" | grep "git_revision" | tr ":" "\n" | sed -n 3p | tr "\"" "\n" | sed -n 1p)" current_flutter_git_revision="$(git -C $ENGINE_DIR/flutter rev-parse HEAD)" if [[ $fuchsia_flutter_git_revision != $current_flutter_git_revision ]] then engine-warning "Your current Flutter Engine commit ($current_flutter_git_revision) is not Fuchsia's Flutter Engine commit ($fuchsia_flutter_git_revision)." engine-warning "You should checkout Fuchsia's Flutter Engine commit. This avoids crashing on app startup from using a different version of the Dart SDK. See https://github.com/flutter/flutter/wiki/Compiling-the-engine#important-dart-version-synchronization-on-fuchsia for more details." engine-warning "You can checkout Fuchsia's Flutter Engine commit by running:" engine-warning '$ENGINE_DIR/flutter/tools/fuchsia/devshell/checkout_fuchsia_revision.sh' engine-warning "If you have already checked out Fuchsia's Flutter Engine commit and then committed some additional changes, please ignore the above warning." fi all_gn_args="--fuchsia --fuchsia-cpu="${fuchsia_cpu}" --runtime-mode="${runtime_mode}" ${goma_flags} ${unoptimized_flags} ${extra_gn_args[@]}" engine-info "GN args: ${all_gn_args}" "$ENGINE_DIR"/flutter/tools/gn ${all_gn_args} fuchsia_out_dir_name=fuchsia_${runtime_mode}${unoptimized_suffix}_${fuchsia_cpu} fuchsia_out_dir="$ENGINE_DIR"/out/"${fuchsia_out_dir_name}" engine-info "Building ${fuchsia_out_dir_name}..." ${ninja_cmd} -C "${fuchsia_out_dir}" flutter/shell/platform/fuchsia fuchsia_tests engine-info "Making Fuchsia's Flutter prebuilts writable..." chmod -R +w "$FUCHSIA_DIR"/prebuilt/third_party/flutter engine-info "Copying the patched SDK (dart:ui, dart:zircon, dart:fuchsia) to Fuchsia..." cp -ra "${fuchsia_out_dir}"/flutter_runner_patched_sdk/* "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/release/aot/flutter_runner_patched_sdk/ engine-info "Registering debug symbols..." # .jiri_root/bin/ffx needs to run from $FUCHSIA_DIR. pushd $FUCHSIA_DIR "$FUCHSIA_DIR"/.jiri_root/bin/ffx debug symbol-index add "${fuchsia_out_dir}"/.build-id --build-dir "${fuchsia_out_dir}" popd # $FUCHSIA_DIR if [[ "${runtime_mode}" == release ]] then flutter_runner_pkg="flutter_jit_product_runner-0.far" engine-info "Copying the Flutter JIT product runner (${flutter_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${flutter_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/release/jit/"${flutter_runner_pkg}" flutter_runner_pkg="flutter_aot_product_runner-0.far" engine-info "Copying the Flutter AOT product runner (${flutter_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${flutter_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/release/aot/"${flutter_runner_pkg}" dart_runner_pkg="dart_jit_product_runner-0.far" engine-info "Copying the Dart JIT product runner (${dart_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${dart_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/release/jit/"${dart_runner_pkg}" dart_runner_pkg="dart_aot_product_runner-0.far" engine-info "Copying the Dart AOT product runner (${dart_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${dart_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/release/aot/"${dart_runner_pkg}" else flutter_runner_pkg="flutter_${compilation_mode}_runner-0.far" engine-info "Copying the Flutter runner (${flutter_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${flutter_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/"${runtime_mode}"/"${compilation_mode}"/"${flutter_runner_pkg}" dart_runner_pkg="dart_${compilation_mode}_runner-0.far" engine-info "Copying the Dart runner (${dart_runner_pkg}) to Fuchsia..." cp "${fuchsia_out_dir}"/"${dart_runner_pkg}" "$FUCHSIA_DIR"/prebuilt/third_party/flutter/"${fuchsia_cpu}"/"${runtime_mode}"/"${compilation_mode}"/"${dart_runner_pkg}" fi # TODO(akbiggs): Warn the developer when their current # Fuchsia configuration (`fx set`) is mismatched with the runner # they just deployed. # TODO(akbiggs): Copy the tests over. I couldn't figure out a glob that grabs all of them. echo "Done. You can now build Fuchsia with your Flutter Engine changes by running:" echo ' cd $FUCHSIA_DIR' # TODO(akbiggs): I'm not sure what example to give for arm64. if [[ "${fuchsia_cpu}" == x64 ]] then if [[ "${runtime_mode}" == debug ]] then echo " fx set terminal.x64" else echo " fx set terminal.x64 --release" fi fi echo ' fx build'
engine/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh/0
{ "file_path": "engine/tools/fuchsia/devshell/build_and_copy_to_fuchsia.sh", "repo_id": "engine", "token_count": 2689 }
418
#!/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. """ Gather all the fuchsia artifacts to a destination directory. """ import argparse import errno import json import os import platform import shutil import subprocess import sys _ARTIFACT_PATH_TO_DST = { 'flutter_jit_runner': 'flutter_jit_runner', 'icudtl.dat': 'data/icudtl.dat', 'dart_runner': 'dart_runner', 'flutter_patched_sdk': 'flutter_patched_sdk' } def EnsureParentExists(path): dir_name, _ = os.path.split(path) if not os.path.exists(dir_name): os.makedirs(dir_name) def CopyPath(src, dst): try: EnsureParentExists(dst) shutil.copytree(src, dst) except OSError as exc: if exc.errno == errno.ENOTDIR: shutil.copy(src, dst) else: raise def CreateMetaPackage(dst_root, far_name): meta = os.path.join(dst_root, 'meta') if not os.path.isdir(meta): os.makedirs(meta) content = {} content['name'] = far_name content['version'] = '0' package = os.path.join(meta, 'package') with open(package, 'w') as out_file: json.dump(content, out_file) def GatherArtifacts(src_root, dst_root, create_meta_package=True): if not os.path.exists(dst_root): os.makedirs(dst_root) else: shutil.rmtree(dst_root) for src_rel, dst_rel in _ARTIFACT_PATH_TO_DST.items(): src_full = os.path.join(src_root, src_rel) dst_full = os.path.join(dst_root, dst_rel) if not os.path.exists(src_full): print('Unable to find artifact: ', str(src_full)) sys.exit(1) CopyPath(src_full, dst_full) if create_meta_package: CreateMetaPackage(dst_root, 'flutter_runner') def main(): parser = argparse.ArgumentParser() parser.add_argument('--artifacts-root', dest='artifacts_root', action='store', required=True) parser.add_argument('--dest-dir', dest='dst_dir', action='store', required=True) args = parser.parse_args() assert os.path.exists(args.artifacts_root) dst_parent = os.path.abspath(os.path.join(args.dst_dir, os.pardir)) assert os.path.exists(dst_parent) GatherArtifacts(args.artifacts_root, args.dst_dir) return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/fuchsia/gather_flutter_runner_artifacts.py/0
{ "file_path": "engine/tools/fuchsia/gather_flutter_runner_artifacts.py", "repo_id": "engine", "token_count": 893 }
419
#!/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 sys, math from operator import itemgetter from itertools import groupby import unicodedata import fontforge NAME = "FlutterTest" # Turn off auto-hinting and enable manual hinting. FreeType skips auto-hinting # if the font's family name is in a hard-coded "tricky" font list. TRICKY_NAME = "MingLiU" EM = 1024 DESCENT = -EM // 4 ASCENT = EM + DESCENT # -143 and 20 are the underline location and width Ahem uses. UPOS = -143 * 1000 // EM UWIDTH = 20 * 1000 // EM ### Font Metadata and Metrics font = fontforge.font() font.familyname = TRICKY_NAME font.fullname = NAME font.fontname = NAME # This sets the relevant fields in the os2 table and hhea table. font.ascent = ASCENT font.descent = -DESCENT font.upos = UPOS font.uwidth = UWIDTH font.hhea_linegap = 0 font.os2_typolinegap = 0 font.horizontalBaseline = ( ("hang", "ideo", "romn"), ( ("latn", "romn", (ASCENT, DESCENT, 0), ()), ("grek", "romn", (ASCENT, DESCENT, 0), ()), ("hani", "ideo", (ASCENT, DESCENT, 0), ()), ), ) ### TrueType Hinting # Hints are ignored on macOS. # # These hints only **vertically** adjust the outlines, for better vertical # alignment in golden tests. They don't affect the font or the glyphs' public # metrics available to the framework, so they typically don't affect non-golden # tests. # # The hinting goals are: # # 1. Aligning the key points on glyph outlines between glyphs, when different # types of glyphs are placed side by side. E.g., for a given point size, "p" # and "É" should never overlap vertically, and "p" and "x" should be # bottom-aligned. # # 2. Aligning the top and the bottom of the "x" glyph with the background. With # point size = 14, since the em square's y-extent is 3.5 px (256 * 14 / 1024) # below the baseline and 10.5 px above the baseline, the glyph's CBOX will be # "rounded out" (3.5 -> 4, 10.5 -> 11). So "x" is going to be misaligned with # the background by +0.5 px when rasterized without proper grid-fitting. # Allocate space in cvt. font.cvt = [0] # gcd is used to avoid overflowing, this works for the current ASCENT and EM value. gcd = math.gcd(ASCENT, EM) # The control value program is for computing the y-offset (in pixels) to move # the embox's top edge to grid. The end result will be stored to CVT entry 0. # CVT[0] = (pointSize * ASCENT / EM) - ceil(pointSize * ASCENT / EM) prep_program = f""" RTG PUSHW_1 0 MPS PUSHW_1 {(ASCENT << 6) // gcd} MUL PUSHW_1 {EM // gcd} DIV DUP CEILING SUB WCVTP """ font.setTableData("prep", fontforge.parseTTInstrs(prep_program)) def glyph_program(glyph): # Shift Zone 1 by CVT[0]. In FreeType SHZ actually shifts the zone zp2 # points to, instead of top of the stack. That's probably a bug. instructions = """ SVTCA[0] PUSHB_4 0 0 0 0 SZPS MIRP[0000] SRP2 PUSHB_3 1 1 1 SZP2 SHZ[0] SZPS """ # Round To Grid every on-curve point, but ignore those who are on the ASCENT # or DESCENT line. This step keeps "p" (ascent flushed) and "É" (descent # flushed)'s y extents from overlapping each other. for index, point in enumerate([p for contour in glyph.foreground for p in contour]): if point.y not in [ASCENT, DESCENT]: instructions += f""" PUSHB_1 {index} MDAP[1] """ return fontforge.parseTTInstrs(instructions) ### Creating Glyphs Outlines def square_glyph(glyph): pen = glyph.glyphPen() # Counter Clockwise pen.moveTo((0, DESCENT)) pen.lineTo((0, ASCENT)) pen.lineTo((EM, ASCENT)) pen.lineTo((EM, DESCENT)) pen.closePath() glyph.ttinstrs = glyph_program(glyph) def ascent_flushed_glyph(glyph): pen = glyph.glyphPen() pen.moveTo((0, DESCENT)) pen.lineTo((0, 0)) pen.lineTo((EM, 0)) pen.lineTo((EM, DESCENT)) pen.closePath() glyph.ttinstrs = glyph_program(glyph) def descent_flushed_glyph(glyph): pen = glyph.glyphPen() pen.moveTo((0, 0)) pen.lineTo((0, ASCENT)) pen.lineTo((EM, ASCENT)) pen.lineTo((EM, 0)) pen.closePath() glyph.ttinstrs = glyph_program(glyph) def not_def_glyph(glyph): pen = glyph.glyphPen() # Counter Clockwise for the outer contour. pen.moveTo((EM // 8, 0)) pen.lineTo((EM // 8, ASCENT)) pen.lineTo((EM - EM // 8, ASCENT)) pen.lineTo((EM - EM // 8, 0)) pen.closePath() # Clockwise, inner contour. pen.moveTo((EM // 4, EM // 8)) pen.lineTo((EM - EM // 4, EM // 8)) pen.lineTo((EM - EM // 4, ASCENT - EM // 8)) pen.lineTo((EM // 4, ASCENT - EM // 8)) pen.closePath() glyph.ttinstrs = glyph_program(glyph) def unicode_range(fromUnicode, throughUnicode): return range(fromUnicode, throughUnicode + 1) square_codepoints = [ codepoint for l in [ unicode_range(0x21, 0x26), unicode_range(0x28, 0x6F), unicode_range(0x71, 0x7E), unicode_range(0xA1, 0xC8), unicode_range(0xCA, 0xFF), [0x131], unicode_range(0x152, 0x153), [0x178, 0x192], unicode_range(0x2C6, 0x2C7), [0x2C9], unicode_range(0x2D8, 0x2DD), [0x394, 0x3A5, 0x3A7, 0x3A9, 0x3BC, 0x3C0], unicode_range(0x2013, 0x2014), unicode_range(0x2018, 0x201A), unicode_range(0x201C, 0x201E), unicode_range(0x2020, 0x2022), [0x2026, 0x2030], unicode_range(0x2039, 0x203A), [0x2044, 0x2122, 0x2126, 0x2202, 0x2206, 0x220F], unicode_range(0x2211, 0x2212), unicode_range(0x2219, 0x221A), [0x221E, 0x222B, 0x2248, 0x2260], unicode_range(0x2264, 0x2265), [ 0x22F2, 0x25CA, 0x3007, 0x4E00, 0x4E03, 0x4E09, 0x4E5D, 0x4E8C, 0x4E94, 0x516B, 0x516D, 0x5341, 0x56D7, 0x56DB, 0x571F, 0x6728, 0x6C34, 0x706B, 0x91D1 ], unicode_range(0xF000, 0xF002), ] for codepoint in l ] + [0x70] + [ord(c) for c in "中文测试文本是否正确"] no_path_codepoints = [ #(codepoint, advance %) (0x0020, 1), (0x00A0, 1), (0x2003, 1), (0x3000, 1), (0x2002, 1 / 2), (0x2004, 1 / 3), (0x2005, 1 / 4), (0x2006, 1 / 6), (0x2009, 1 / 5), (0x200A, 1 / 10), (0xFEFF, 0), (0x200B, 0), (0x200C, 0), (0x200D, 0), ] def create_glyph(name, contour): glyph = font.createChar(-1, name) contour(glyph) glyph.width = EM return glyph if square_codepoints: create_glyph("Square", square_glyph).altuni = square_codepoints create_glyph("Ascent Flushed", ascent_flushed_glyph).unicode = 0x70 create_glyph("Descent Flushed", descent_flushed_glyph).unicode = 0xC9 create_glyph(".notdef", not_def_glyph).unicode = -1 def create_no_path_glyph(codepoint, advance_percentage): name = "Zero Advance" if advance_percentage == 0 else ( "Full Advance" if advance_percentage == 1 else f"1/{(int)(1/advance_percentage)} Advance" ) no_path_glyph = font.createChar(codepoint, name) no_path_glyph.width = (int)(EM * advance_percentage) return no_path_glyph for (codepoint, advance_percentage) in no_path_codepoints: if (codepoint in square_codepoints): raise ValueError(f"{hex(codepoint)} is occupied.") create_no_path_glyph(codepoint, advance_percentage) font.generate(sys.argv[1] if len(sys.argv) >= 2 else "test_font.ttf") ### Printing Glyph Map Stats scripts = set() for glyph in font.glyphs(): if glyph.unicode >= 0: scripts.add(fontforge.scriptFromUnicode(glyph.unicode)) for codepoint, _, _ in glyph.altuni or []: scripts.add(fontforge.scriptFromUnicode(codepoint)) script_list = list(scripts) script_list.sort() print(f"| \ Script <br />Glyph | {' | '.join(script_list)} |") print(" | :--- " + " | :----: " * len(script_list) + "|") for glyph in font.glyphs(): if glyph.unicode < 0 and not glyph.altuni: continue glyph_mapping = {} if glyph.unicode >= 0: glyph_mapping[fontforge.scriptFromUnicode(glyph.unicode)] = [glyph.unicode] for codepoint, _, _ in glyph.altuni or []: script = fontforge.scriptFromUnicode(codepoint) if script in glyph_mapping: glyph_mapping[script].append(codepoint) else: glyph_mapping[script] = [codepoint] codepoints_by_script = [glyph_mapping.get(script, []) for script in script_list] def describe_codepoint_range(codepoints): if not codepoints: return "" codepoints.sort() codepoint_ranges = [ list(map(itemgetter(1), group)) for key, group in groupby(enumerate(codepoints), lambda x: x[0] - x[1]) ] characters = [chr(c) for c in codepoints] def map_char(c): if c == "`": return "`` ` ``" if c == "|": return "`\\|`" if c.isprintable() and (not c.isspace()): return f"`{c}`" return "`<" + unicodedata.name(c, hex(ord(c))) + ">`" full_list = " ".join([map_char(c) for c in characters]) return "**codepoint(s):** " + ", ".join([ f"{hex(r[0])}-{hex(r[-1])}" if len(r) > 1 else hex(r[0]) for r in codepoint_ranges ]) + "<br />" + "**character(s):** " + full_list print( f"| {glyph.glyphname} | {' | '.join([describe_codepoint_range(l) for l in codepoints_by_script])} |" )
engine/tools/gen_test_font.py/0
{ "file_path": "engine/tools/gen_test_font.py", "repo_id": "engine", "token_count": 4167 }
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. import 'package:args/command_runner.dart'; import 'messages.dart'; /// The command that implements the post-merge githook class PostMergeCommand extends Command<bool> { @override final String name = 'post-merge'; @override final String description = 'Checks to run after a "git merge"'; @override Future<bool> run() async { printGclientSyncReminder(name); return true; } }
engine/tools/githooks/lib/src/post_merge_command.dart/0
{ "file_path": "engine/tools/githooks/lib/src/post_merge_command.dart", "repo_id": "engine", "token_count": 173 }
421
include: ../../analysis_options.yaml
engine/tools/golden_tests_harvester/analysis_options.yaml/0
{ "file_path": "engine/tools/golden_tests_harvester/analysis_options.yaml", "repo_id": "engine", "token_count": 12 }
422
# path_ops A small library that exposes C bindings for Skia's SkPathOps, with a minimal interface for SkPath. This library only supports four commands from SkPath: `moveTo`, `lineTo`, `cubicTo`, and `close`. This library is a subset of the functionality provided by Skia's `PathKit` library. It is primarily intended for use with the `vector_graphics` optimizing compiler. That library uses this one to optimize certain masking and clipping operations at compile time.
engine/tools/path_ops/README.md/0
{ "file_path": "engine/tools/path_ops/README.md", "repo_id": "engine", "token_count": 122 }
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. import 'package:engine_build_configs/src/build_config.dart'; import 'package:engine_build_configs/src/build_config_loader.dart'; import 'package:file/file.dart'; import 'package:file/memory.dart'; import 'package:litetest/litetest.dart'; import 'fixtures.dart' as fixtures; int main() { test('BuildConfigLoader can load a build config', () { final FileSystem fs = MemoryFileSystem(); final String buildConfigPath = fs.path.join('flutter', 'ci', 'builders'); final Directory buildConfigsDir = fs.directory(buildConfigPath); final File buildConfigFile = buildConfigsDir.childFile( 'linux_test_build.json', ); buildConfigFile.create(recursive: true); buildConfigFile.writeAsStringSync(fixtures.buildConfigJson); final BuildConfigLoader loader = BuildConfigLoader( buildConfigsDir: buildConfigsDir, ); expect(loader.configs, isNotNull); expect(loader.errors, isEmpty); expect(loader.configs['linux_test_build'], isNotNull); }); test('BuildConfigLoader gives an empty config when no configs found', () { final FileSystem fs = MemoryFileSystem(); final String buildConfigPath = fs.path.join( 'flutter', 'ci', 'builders', 'linux_test_build.json', ); final Directory buildConfigsDir = fs.directory(buildConfigPath); final BuildConfigLoader loader = BuildConfigLoader( buildConfigsDir: buildConfigsDir, ); expect(loader.configs, isNotNull); expect( loader.errors[0], equals( 'flutter/ci/builders/linux_test_build.json does not exist.', )); expect(loader.configs, equals(<String, BuilderConfig>{})); }); return 0; }
engine/tools/pkg/engine_build_configs/test/build_config_loader_test.dart/0
{ "file_path": "engine/tools/pkg/engine_build_configs/test/build_config_loader_test.dart", "repo_id": "engine", "token_count": 645 }
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. # This python script uses `pub get --offline` to fill in # .dart_tool/package_config.json files for Dart packages in the tree whose # dependencies should be entirely resolved without requesting data from pub.dev. # This allows us to be certain that the Dart code we are pulling for these # packages is explicitly fetched by `gclient sync` rather than implicitly # fetched by pub version solving, and pub fetching transitive dependencies. import json import os import subprocess import sys SRC_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) ENGINE_DIR = os.path.join(SRC_ROOT, 'flutter') ALL_PACKAGES = [ os.path.join(ENGINE_DIR, 'ci'), os.path.join(ENGINE_DIR, 'flutter_frontend_server'), os.path.join(ENGINE_DIR, 'impeller', 'tessellator', 'dart'), os.path.join(ENGINE_DIR, 'shell', 'vmservice'), os.path.join(ENGINE_DIR, 'testing', 'android_background_image'), os.path.join(ENGINE_DIR, 'testing', 'benchmark'), os.path.join(ENGINE_DIR, 'testing', 'dart'), os.path.join(ENGINE_DIR, 'testing', 'litetest'), os.path.join(ENGINE_DIR, 'testing', 'scenario_app'), os.path.join(ENGINE_DIR, 'testing', 'skia_gold_client'), os.path.join(ENGINE_DIR, 'testing', 'smoke_test_failure'), os.path.join(ENGINE_DIR, 'testing', 'symbols'), os.path.join(ENGINE_DIR, 'tools', 'android_lint'), os.path.join(ENGINE_DIR, 'tools', 'api_check'), os.path.join(ENGINE_DIR, 'tools', 'build_bucket_golden_scraper'), os.path.join(ENGINE_DIR, 'tools', 'clang_tidy'), os.path.join(ENGINE_DIR, 'tools', 'compare_goldens'), os.path.join(ENGINE_DIR, 'tools', 'const_finder'), os.path.join(ENGINE_DIR, 'tools', 'dir_contents_diff'), os.path.join(ENGINE_DIR, 'tools', 'engine_tool'), os.path.join(ENGINE_DIR, 'tools', 'gen_web_locale_keymap'), os.path.join(ENGINE_DIR, 'tools', 'githooks'), os.path.join(ENGINE_DIR, 'tools', 'golden_tests_harvester'), os.path.join(ENGINE_DIR, 'tools', 'header_guard_check'), os.path.join(ENGINE_DIR, 'tools', 'licenses'), os.path.join(ENGINE_DIR, 'tools', 'path_ops', 'dart'), os.path.join(ENGINE_DIR, 'tools', 'pkg', 'engine_build_configs'), os.path.join(ENGINE_DIR, 'tools', 'pkg', 'engine_repo_tools'), os.path.join(ENGINE_DIR, 'tools', 'pkg', 'git_repo_tools'), os.path.join(ENGINE_DIR, 'tools', 'pkg', 'process_fakes'), ] def fetch_package(pub, package): try: subprocess.check_output(pub, cwd=package, stderr=subprocess.STDOUT) except subprocess.CalledProcessError as err: print( '"%s" failed in "%s" with status %d:\n%s' % (' '.join(pub), package, err.returncode, err.output) ) return 1 return 0 def check_package(package): package_config = os.path.join(package, '.dart_tool', 'package_config.json') pub_count = 0 with open(package_config) as config_file: data_dict = json.load(config_file) packages_data = data_dict['packages'] for package_data in packages_data: package_uri = package_data['rootUri'] package_name = package_data['name'] if '.pub-cache' in package_uri and ('pub.dartlang.org' in package_uri or 'pub.dev' in package_uri): print('Error: package "%s" was fetched from pub' % package_name) pub_count = pub_count + 1 if pub_count > 0: print('Error: %d packages were fetched from pub for %s' % (pub_count, package)) print( 'Please fix the pubspec.yaml for %s ' 'so that all dependencies are path dependencies' % package ) return pub_count EXCLUDED_DIRS = [ os.path.join(ENGINE_DIR, 'lib'), os.path.join(ENGINE_DIR, 'prebuilts'), os.path.join(ENGINE_DIR, 'shell', 'platform', 'fuchsia'), os.path.join(ENGINE_DIR, 'shell', 'vmservice'), os.path.join(ENGINE_DIR, 'sky', 'packages'), os.path.join(ENGINE_DIR, 'third_party'), os.path.join(ENGINE_DIR, 'web_sdk'), ] # Returns a list of paths to directories containing pubspec.yaml files that # are not listed in ALL_PACKAGES. Directory trees under the paths in # EXCLUDED_DIRS are skipped. def find_unlisted_packages(): unlisted = [] for root, dirs, files in os.walk(ENGINE_DIR): excluded = [] for dirname in dirs: full_dirname = os.path.join(root, dirname) if full_dirname in EXCLUDED_DIRS: excluded.append(dirname) for exclude in excluded: dirs.remove(exclude) for filename in files: if filename == 'pubspec.yaml': if root not in ALL_PACKAGES: unlisted.append(root) return unlisted def main(): dart_sdk_bin = os.path.join(SRC_ROOT, 'third_party', 'dart', 'tools', 'sdks', 'dart-sdk', 'bin') # Ensure all relevant packages are listed in ALL_PACKAGES. unlisted = find_unlisted_packages() if len(unlisted) > 0: for pkg in unlisted: print('The Dart package "%s" must be checked in flutter/tools/pub_get_offline.py' % pkg) return 1 dart = 'dart' if os.name == 'nt': dart = 'dart.exe' pubcmd = [os.path.join(dart_sdk_bin, dart), 'pub', '--suppress-analytics', 'get', '--offline'] pub_count = 0 for package in ALL_PACKAGES: if fetch_package(pubcmd, package) != 0: return 1 pub_count = pub_count + check_package(package) if pub_count > 0: return 1 return 0 if __name__ == '__main__': sys.exit(main())
engine/tools/pub_get_offline.py/0
{ "file_path": "engine/tools/pub_get_offline.py", "repo_id": "engine", "token_count": 2190 }
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 "vulkan_application.h" #include <utility> #include <vector> #include "flutter/vulkan/procs/vulkan_proc_table.h" #include "vulkan_device.h" #include "vulkan_utilities.h" namespace vulkan { VulkanApplication::VulkanApplication( VulkanProcTable& p_vk, // NOLINT const std::string& application_name, std::vector<std::string> enabled_extensions, uint32_t application_version, uint32_t api_version, bool enable_validation_layers) : vk_(p_vk), api_version_(api_version), valid_(false), enable_validation_layers_(enable_validation_layers) { // Check if we want to enable debugging. std::vector<VkExtensionProperties> supported_extensions = GetSupportedInstanceExtensions(vk_); bool enable_instance_debugging = enable_validation_layers_ && ExtensionSupported(supported_extensions, VulkanDebugReport::DebugExtensionName()); // Configure extensions. if (enable_instance_debugging) { enabled_extensions.emplace_back(VulkanDebugReport::DebugExtensionName()); } #if OS_FUCHSIA if (ExtensionSupported(supported_extensions, VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME)) { // VK_KHR_get_physical_device_properties2 is a dependency of the memory // capabilities extension, so the validation layers require that it be // enabled. enabled_extensions.emplace_back( VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME); enabled_extensions.emplace_back( VK_KHR_EXTERNAL_MEMORY_CAPABILITIES_EXTENSION_NAME); } #endif std::vector<const char*> extensions; for (size_t i = 0; i < enabled_extensions.size(); i++) { extensions.push_back(enabled_extensions[i].c_str()); } // Configure layers. const std::vector<std::string> enabled_layers = InstanceLayersToEnable(vk_, 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()); } // Configure init structs. const VkApplicationInfo info = { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, .pNext = nullptr, .pApplicationName = application_name.c_str(), .applicationVersion = application_version, .pEngineName = "FlutterEngine", .engineVersion = VK_MAKE_VERSION(1, 0, 0), .apiVersion = api_version_, }; const VkInstanceCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pNext = nullptr, .flags = 0, .pApplicationInfo = &info, .enabledLayerCount = static_cast<uint32_t>(layers.size()), .ppEnabledLayerNames = layers.data(), .enabledExtensionCount = static_cast<uint32_t>(extensions.size()), .ppEnabledExtensionNames = extensions.data(), }; // Perform initialization. VkInstance instance = VK_NULL_HANDLE; if (VK_CALL_LOG_ERROR(vk_.CreateInstance(&create_info, nullptr, &instance)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not create application instance."; return; } // Now that we have an instance, set up instance proc table entries. if (!vk_.SetupInstanceProcAddresses(VulkanHandle<VkInstance>(instance))) { FML_DLOG(INFO) << "Could not set up instance proc addresses."; return; } instance_ = VulkanHandle<VkInstance>{instance, [this](VkInstance i) { FML_DLOG(INFO) << "Destroying Vulkan instance"; vk_.DestroyInstance(i, nullptr); }}; if (enable_instance_debugging) { auto debug_report = std::make_unique<VulkanDebugReport>(vk_, instance_); if (!debug_report->IsValid()) { FML_DLOG(INFO) << "Vulkan debugging was enabled but could not be set up " "for this instance."; } else { debug_report_ = std::move(debug_report); FML_DLOG(INFO) << "Debug reporting is enabled."; } } valid_ = true; } VulkanApplication::~VulkanApplication() = default; bool VulkanApplication::IsValid() const { return valid_; } uint32_t VulkanApplication::GetAPIVersion() const { return api_version_; } const VulkanHandle<VkInstance>& VulkanApplication::GetInstance() const { return instance_; } void VulkanApplication::ReleaseInstanceOwnership() { instance_.ReleaseOwnership(); } std::vector<VkPhysicalDevice> VulkanApplication::GetPhysicalDevices() const { if (!IsValid()) { return {}; } uint32_t device_count = 0; if (VK_CALL_LOG_ERROR(vk_.EnumeratePhysicalDevices(instance_, &device_count, nullptr)) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not enumerate physical device."; return {}; } if (device_count == 0) { // No available devices. FML_DLOG(INFO) << "No physical devices found."; return {}; } std::vector<VkPhysicalDevice> physical_devices; physical_devices.resize(device_count); if (VK_CALL_LOG_ERROR(vk_.EnumeratePhysicalDevices( instance_, &device_count, physical_devices.data())) != VK_SUCCESS) { FML_DLOG(INFO) << "Could not enumerate physical device."; return {}; } return physical_devices; } std::unique_ptr<VulkanDevice> VulkanApplication::AcquireFirstCompatibleLogicalDevice() const { for (auto device_handle : GetPhysicalDevices()) { auto logical_device = std::make_unique<VulkanDevice>( vk_, VulkanHandle<VkPhysicalDevice>(device_handle), enable_validation_layers_); if (logical_device->IsValid()) { return logical_device; } } FML_DLOG(INFO) << "Could not acquire compatible logical device."; return nullptr; } std::vector<VkExtensionProperties> VulkanApplication::GetSupportedInstanceExtensions( const VulkanProcTable& vk) const { if (!vk.EnumerateInstanceExtensionProperties) { return std::vector<VkExtensionProperties>(); } uint32_t count = 0; if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceExtensionProperties( nullptr, &count, nullptr)) != VK_SUCCESS) { return std::vector<VkExtensionProperties>(); } if (count == 0) { return std::vector<VkExtensionProperties>(); } std::vector<VkExtensionProperties> properties; properties.resize(count); if (VK_CALL_LOG_ERROR(vk.EnumerateInstanceExtensionProperties( nullptr, &count, properties.data())) != VK_SUCCESS) { return std::vector<VkExtensionProperties>(); } return properties; } bool VulkanApplication::ExtensionSupported( const std::vector<VkExtensionProperties>& supported_instance_extensions, const std::string& extension_name) { uint32_t count = supported_instance_extensions.size(); for (size_t i = 0; i < count; i++) { if (strncmp(supported_instance_extensions[i].extensionName, extension_name.c_str(), extension_name.size()) == 0) { return true; } } return false; } } // namespace vulkan
engine/vulkan/vulkan_application.cc/0
{ "file_path": "engine/vulkan/vulkan_application.cc", "repo_id": "engine", "token_count": 2778 }
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. #include "vulkan_provider.h" namespace vulkan { vulkan::VulkanHandle<VkFence> VulkanProvider::CreateFence() { const VkFenceCreateInfo create_info = { .sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = nullptr, .flags = 0, }; VkFence fence; if (VK_CALL_LOG_ERROR(vk().CreateFence(vk_device(), &create_info, nullptr, &fence)) != VK_SUCCESS) return vulkan::VulkanHandle<VkFence>(); return {fence, [this](VkFence fence) { vk().DestroyFence(vk_device(), fence, nullptr); }}; } } // namespace vulkan
engine/vulkan/vulkan_provider.cc/0
{ "file_path": "engine/vulkan/vulkan_provider.cc", "repo_id": "engine", "token_count": 328 }
427
# Copyright (c) 2017, 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 libraries file is only used for building the ddc kernel. # # Note: if you edit this file, you must also edit libraries.json in this # directory: # #. dart third_party/dart/tools/yaml2json.dart flutter/web_sdk/libraries.yaml flutter/web_sdk/libraries.json # # We currently have several different files that needs to be updated when # changing libraries, sources, and patch files. See # https://github.com/dart-lang/sdk/issues/28836. dartdevc: include: - {path: "../dart-sdk/lib/libraries.json", target: dartdevc} libraries: ui: uri: "lib/ui/ui.dart" ui_web: uri: "lib/ui_web/ui_web.dart" _engine: uri: "lib/_engine/engine.dart" _skwasm_stub: uri: "lib/_skwasm_stub/skwasm_stub.dart" _web_unicode: uri: "lib/_web_unicode/web_unicode.dart" _web_locale_keymap: uri: "lib/_web_locale_keymap/web_locale_keymap.dart" _web_test_fonts: uri: "lib/_web_test_fonts/web_test_fonts.dart" dart2js: include: - {path: "../dart-sdk/lib/libraries.json", target: dart2js} libraries: ui: uri: "lib/ui/ui.dart" ui_web: uri: "lib/ui_web/ui_web.dart" _engine: uri: "lib/_engine/engine.dart" _skwasm_stub: uri: "lib/_skwasm_stub/skwasm_stub.dart" _web_unicode: uri: "lib/_web_unicode/web_unicode.dart" _web_locale_keymap: uri: "lib/_web_locale_keymap/web_locale_keymap.dart" _web_test_fonts: uri: "lib/_web_test_fonts/web_test_fonts.dart" wasm: include: - {path: "../dart-sdk/lib/libraries.json", target: wasm} libraries: ui: uri: "lib/ui/ui.dart" ui_web: uri: "lib/ui_web/ui_web.dart" _engine: uri: "lib/_engine/engine.dart" _skwasm_impl: uri: "lib/_skwasm_impl/skwasm_impl.dart" _web_unicode: uri: "lib/_web_unicode/web_unicode.dart" _web_locale_keymap: uri: "lib/_web_locale_keymap/web_locale_keymap.dart" _web_test_fonts: uri: "lib/_web_test_fonts/web_test_fonts.dart"
engine/web_sdk/libraries.yaml/0
{ "file_path": "engine/web_sdk/libraries.yaml", "repo_id": "engine", "token_count": 1057 }
428
name: web_test_utils # Keep the SDK version range in sync with lib/web_ui/pubspec.yaml environment: sdk: '>=3.2.0-0 <4.0.0' dependencies: collection: 1.17.0 crypto: 3.0.1 image: 3.0.1 js: 0.6.4 meta: ^1.7.0 path: 1.8.0 process: 4.2.3 skia_gold_client: path: ../../testing/skia_gold_client typed_data: 1.3.0 yaml: 3.0.0 dependency_overrides: engine_repo_tools: path: ../../tools/pkg/engine_repo_tools
engine/web_sdk/web_test_utils/pubspec.yaml/0
{ "file_path": "engine/web_sdk/web_test_utils/pubspec.yaml", "repo_id": "engine", "token_count": 208 }
429
<project version="4"> <component name="ClientPropertiesManager"> <properties class="javax.swing.JPanel"> <property name="BorderFactoryClass" class="java.lang.String" /> </properties> </component> <component name="ExternalStorageConfigurationManager" enabled="true" /> <component name="FrameworkDetectionExcludesConfiguration"> <file type="web" url="file://$PROJECT_DIR$" /> </component> <component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK"> <output url="file://$PROJECT_DIR$/out" /> </component> </project>
flutter-intellij/.idea/misc.xml/0
{ "file_path": "flutter-intellij/.idea/misc.xml", "repo_id": "flutter-intellij", "token_count": 202 }
430
#!/bin/bash # TODO: Warn if 'pub get' needs to be done. dart tool/plugin/bin/main.dart "$@"
flutter-intellij/bin/plugin/0
{ "file_path": "flutter-intellij/bin/plugin", "repo_id": "flutter-intellij", "token_count": 40 }
431
/* * 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.tests.gui import com.intellij.testGuiFramework.framework.GuiTestSuite import com.intellij.testGuiFramework.framework.GuiTestSuiteRunner import org.junit.runner.RunWith import org.junit.runners.Suite //* gradle -Dtest.single=TestSuite clean test -Didea.gui.test.alternativeIdePath="<path_to_installed_IDE>" // The log file is at flutter-gui-tests/build/idea-sandbox/system/log/idea.log // The test report is at flutter-gui-tests/build/reports/tests/test/index.html @RunWith(GuiTestSuiteRunner::class) @Suite.SuiteClasses(SmokeTest::class, InspectorTest::class, PerfTest::class) class TestSuite : GuiTestSuite()
flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/TestSuite.kt/0
{ "file_path": "flutter-intellij/flutter-gui-tests/testSrc/io/flutter/tests/gui/TestSuite.kt", "repo_id": "flutter-intellij", "token_count": 271 }
432
/* * 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; import com.google.common.base.Charsets; import com.intellij.execution.ExecutionException; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.util.ExecUtil; import com.intellij.ide.actions.ShowSettingsUtilImpl; import com.intellij.ide.impl.ProjectUtil; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationInfo; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.extensions.PluginId; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.roots.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.testFramework.LightVirtualFile; import com.intellij.util.PlatformUtils; import com.jetbrains.lang.dart.DartFileType; import com.jetbrains.lang.dart.psi.DartFile; import io.flutter.jxbrowser.EmbeddedJxBrowser; import io.flutter.jxbrowser.JxBrowserStatus; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRootCache; import io.flutter.settings.FlutterSettings; import io.flutter.utils.AndroidUtils; import io.flutter.utils.FlutterModuleUtils; import io.flutter.view.EmbeddedBrowser; import io.flutter.view.EmbeddedJcefBrowser; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.SystemIndependent; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.LoaderOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.constructor.SafeConstructor; import org.yaml.snakeyaml.nodes.Tag; import org.yaml.snakeyaml.representer.Representer; import org.yaml.snakeyaml.resolver.Resolver; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Paths; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.regex.Pattern; public class FlutterUtils { public static class FlutterPubspecInfo { private final long modificationStamp; private boolean flutter = false; private boolean plugin = false; FlutterPubspecInfo(long modificationStamp) { this.modificationStamp = modificationStamp; } public boolean declaresFlutter() { return flutter; } public boolean isFlutterPlugin() { return plugin; } public long getModificationStamp() { return modificationStamp; } } private static final Pattern VALID_ID = Pattern.compile("[_a-zA-Z$][_a-zA-Z0-9$]*"); // Note the possessive quantifiers -- greedy quantifiers are too slow on long expressions (#1421). private static final Pattern VALID_PACKAGE = Pattern.compile("^([a-z]++([_]?[a-z0-9]+)*)++$"); private FlutterUtils() { } /** * This method exists for compatibility with older IntelliJ API versions. * <p> * `Application.invokeAndWait(Runnable)` doesn't exist pre 2016.3. */ public static void invokeAndWait(@NotNull Runnable runnable) throws ProcessCanceledException { ApplicationManager.getApplication().invokeAndWait( runnable, ModalityState.defaultModalityState()); } public static boolean isFlutteryFile(@NotNull VirtualFile file) { return isDartFile(file) || PubRoot.isPubspec(file); } public static boolean couldContainWidgets(@Nullable VirtualFile file) { // Skip temp file used to show things like files downloaded from the VM. if (file instanceof LightVirtualFile) { return false; } // TODO(jacobr): we might also want to filter for files not under the current project root. return file != null && isDartFile(file); } public static boolean isDartFile(@NotNull VirtualFile file) { return Objects.equals(file.getFileType(), DartFileType.INSTANCE); } public static boolean isAndroidStudio() { return StringUtil.equals(PlatformUtils.getPlatformPrefix(), "AndroidStudio"); } /** * Write a warning message to the IntelliJ log. * <p> * This is separate from LOG.warn() to allow us to decorate the behavior. */ public static void warn(Logger logger, @NotNull Throwable t) { logger.warn(t); } /** * Write a warning message to the IntelliJ log. * <p> * This is separate from LOG.warn() to allow us to decorate the behavior. */ public static void warn(Logger logger, String message) { logger.warn(message); } /** * Write a warning message to the IntelliJ log. * <p> * This is separate from LOG.warn() to allow us to decorate the behavior. */ public static void warn(Logger logger, String message, @NotNull Throwable t) { logger.warn(message, t); } private static int getBaselineVersion() { final ApplicationInfo appInfo = ApplicationInfo.getInstance(); if (appInfo != null) { return appInfo.getBuild().getBaselineVersion(); } return -1; } public static void disableGradleProjectMigrationNotification(@NotNull Project project) { final String showMigrateToGradlePopup = "show.migrate.to.gradle.popup"; final PropertiesComponent properties = PropertiesComponent.getInstance(project); if (properties.getValue(showMigrateToGradlePopup) == null) { properties.setValue(showMigrateToGradlePopup, "false"); } } public static boolean exists(@Nullable VirtualFile file) { return file != null && file.exists(); } /** * Test if the given element is contained in a module with a pub root that declares a flutter dependency. */ public static boolean isInFlutterProject(@NotNull Project project, @NotNull PsiElement element) { final PsiFile file = element.getContainingFile(); final PubRoot pubRoot; if (file == null) { if (element instanceof PsiDirectory) { pubRoot = PubRootCache.getInstance(project).getRoot(((PsiDirectory)element).getVirtualFile()); } else { return false; } } else { pubRoot = PubRootCache.getInstance(project).getRoot(file); } if (pubRoot == null) { return false; } return pubRoot.declaresFlutter(); } public static boolean isInTestDir(@Nullable DartFile file) { if (file == null) return false; // Check that we're in a pub root. final PubRoot root = PubRootCache.getInstance(file.getProject()).getRoot(file.getVirtualFile().getParent()); if (root == null) return false; //noinspection ConstantConditions VirtualFile dir = file.getVirtualFile().getParent(); if (dir == null) { return false; } final Module module = root.getModule(file.getProject()); if (!root.hasTests(dir)) { if (!isInTestOrSourceRoot(module, file)) { return false; } } // Check that we're in a Flutter module. return FlutterModuleUtils.isFlutterModule(module); } private static boolean isInTestOrSourceRoot(@Nullable Module module, @NotNull DartFile file) { if (module == null) { return false; } final ModuleRootManager manager = ModuleRootManager.getInstance(module); if (manager == null) { return false; } final ContentEntry[] entries = manager.getContentEntries(); final VirtualFile virtualFile = file.getContainingFile().getVirtualFile(); boolean foundSourceRoot = false; for (ContentEntry entry : entries) { for (SourceFolder folder : entry.getSourceFolders()) { final VirtualFile folderFile = folder.getFile(); if (folderFile == null) { continue; } if (folderFile.equals(VfsUtil.getCommonAncestor(folderFile, virtualFile))) { if (folder.getRootType().isForTests()) { return true; // Test file is in a directory marked as a test source root, but not named 'test'. } else { foundSourceRoot = true; break; } } } } if (foundSourceRoot) { // The file is in a sources root but not marked as tests. if (file.getName().endsWith(("_test.dart")) && FlutterSettings.getInstance().isAllowTestsInSourcesRoot()) { return true; } } return false; } public static boolean isIntegrationTestingMode() { return System.getProperty("idea.required.plugins.id", "").equals("io.flutter.tests.gui.flutter-gui-tests"); } @Nullable public static VirtualFile getRealVirtualFile(@Nullable PsiFile psiFile) { return psiFile != null ? psiFile.getOriginalFile().getVirtualFile() : null; } @NotNull public static VirtualFile getProjectRoot(@NotNull Project project) { assert !project.isDefault(); @SystemIndependent final String path = project.getBasePath(); assert path != null; final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path); return Objects.requireNonNull(file); } /** * Returns the Dart file for the given PsiElement, or null if not a match. */ @Nullable public static DartFile getDartFile(final @Nullable PsiElement elt) { if (elt == null) return null; final PsiFile psiFile = elt.getContainingFile(); if (!(psiFile instanceof DartFile)) return null; return (DartFile)psiFile; } public static void openFlutterSettings(@Nullable Project project) { ShowSettingsUtilImpl.showSettingsDialog(project, FlutterConstants.FLUTTER_SETTINGS_PAGE_ID, ""); } /** * Checks whether a given string is a Dart keyword. * * @param string the string to check * @return true if a keyword, false otherwise */ public static boolean isDartKeyword(@NotNull String string) { return FlutterConstants.DART_KEYWORDS.contains(string); } /** * Checks whether a given string is a valid Dart identifier. * <p> * See: https://dart.dev/guides/language/spec * * @param id the string to check * @return true if a valid identifer, false otherwise. */ public static boolean isValidDartIdentifier(@NotNull String id) { return VALID_ID.matcher(id).matches(); } /** * Checks whether a given string is a valid Dart package name. * <p> * * @param name the string to check * @return true if a valid package name, false otherwise. * @see <a href="dart.dev/tools/pub/pubspec#name">https://dart.dev/tools/pub/pubspec#name</a> */ public static boolean isValidPackageName(@NotNull String name) { return VALID_PACKAGE.matcher(name).matches(); } /** * Checks whether a given filename is an Xcode metadata file, suitable for opening externally. * * @param name the name to check * @return true if an xcode project filename */ public static boolean isXcodeFileName(@NotNull String name) { return isXcodeProjectFileName(name) || isXcodeWorkspaceFileName(name); } /** * Checks whether a given file name is an Xcode project filename. * * @param name the name to check * @return true if an xcode project filename */ public static boolean isXcodeProjectFileName(@NotNull String name) { return name.endsWith(".xcodeproj"); } /** * Checks whether a given name is an Xcode workspace filename. * * @param name the name to check * @return true if an xcode workspace filename */ public static boolean isXcodeWorkspaceFileName(@NotNull String name) { return name.endsWith(".xcworkspace"); } /** * Checks whether the given commandline executes cleanly. * * @param cmd the command * @return true if the command runs cleanly */ public static boolean runsCleanly(@NotNull GeneralCommandLine cmd) { try { return ExecUtil.execAndGetOutput(cmd).getExitCode() == 0; } catch (ExecutionException e) { return false; } } @NotNull public static PluginId getPluginId() { final PluginId pluginId = PluginId.findId("io.flutter", ""); assert pluginId != null; return pluginId; } /** * Given some plugin id, this method returns the {@link IdeaPluginDescriptor}, or null if the plugin is not installed. */ @Nullable public static IdeaPluginDescriptor getPluginDescriptor(@NotNull String pluginId) { for (IdeaPluginDescriptor descriptor : PluginManagerCore.getPlugins()) { if (descriptor.getPluginId().getIdString().equals(pluginId)) { return descriptor; } } return null; } /** * Returns a structured object with information about the Flutter properties of the given * pubspec file. */ public static FlutterPubspecInfo getFlutterPubspecInfo(@NotNull final VirtualFile pubspec) { // It uses Flutter if it contains 'dependencies: flutter'. // It's a plugin if it contains 'flutter: plugin'. final FlutterPubspecInfo info = new FlutterPubspecInfo(pubspec.getModificationStamp()); try { final Map<String, Object> yamlMap = readPubspecFileToMap(pubspec); if (yamlMap != null) { // Special case the 'flutter' package itself - this allows us to run their unit tests from IntelliJ. final Object packageName = yamlMap.get("name"); if ("flutter".equals(packageName)) { info.flutter = true; } // Check the dependencies. final Object dependencies = yamlMap.get("dependencies"); if (dependencies instanceof Map) { // We use `|=` for assigning to 'flutter' below as it might have been assigned to true above. info.flutter |= ((Map<?, ?>)dependencies).containsKey("flutter"); } // Check for a Flutter plugin. final Object flutterEntry = yamlMap.get("flutter"); if (flutterEntry instanceof Map) { info.plugin = ((Map<?, ?>)flutterEntry).containsKey("plugin"); } } } catch (IOException e) { // ignore } return info; } /** * Returns true if passed pubspec declares a flutter dependency. */ public static boolean declaresFlutter(@NotNull final VirtualFile pubspec) { return getFlutterPubspecInfo(pubspec).declaresFlutter(); } /** * Returns true if the passed pubspec indicates that it is a Flutter plugin. */ public static boolean isFlutterPlugin(@NotNull final VirtualFile pubspec) { return getFlutterPubspecInfo(pubspec).isFlutterPlugin(); } /** * Return the project located at the <code>path</code> or containing it. * * @param path The path to a project or one of its files * @return The Project located at the path */ @Nullable public static Project findProject(@NotNull String path) { for (Project project : ProjectManager.getInstance().getOpenProjects()) { if (ProjectUtil.isSameProject(Paths.get(path), project)) { return project; } } return null; } private static Map<String, Object> readPubspecFileToMap(@NotNull final VirtualFile pubspec) throws IOException { final String contents = new String(pubspec.contentsToByteArray(true /* cache contents */)); return loadPubspecInfo(contents); } private static Map<String, Object> loadPubspecInfo(@NotNull String yamlContents) { final Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()), new Representer(new DumperOptions()), new DumperOptions(), new Resolver() { @Override protected void addImplicitResolvers() { this.addImplicitResolver(Tag.BOOL, BOOL, "yYnNtTfFoO"); this.addImplicitResolver(Tag.NULL, NULL, "~nN\u0000"); this.addImplicitResolver(Tag.NULL, EMPTY, null); this.addImplicitResolver(new Tag("tag:yaml.org,2002:value"), VALUE, "="); this.addImplicitResolver(Tag.MERGE, MERGE, "<"); } }); try { return yaml.load(yamlContents); } catch (Exception e) { return null; } } public static boolean isAndroidxProject(@NotNull Project project) { @SystemIndependent final String basePath = project.getBasePath(); assert basePath != null; final VirtualFile projectDir = LocalFileSystem.getInstance().findFileByPath(basePath); assert projectDir != null; VirtualFile androidDir = getFlutterManagedAndroidDir(projectDir); if (androidDir == null) { androidDir = getAndroidProjectDir(projectDir); if (androidDir == null) { return false; } } final VirtualFile propFile = androidDir.findChild("gradle.properties"); if (propFile == null) { return false; } final Properties properties = new Properties(); try { properties.load(new InputStreamReader(propFile.getInputStream(), Charsets.UTF_8)); } catch (IOException ex) { return false; } final String value = properties.getProperty("android.useAndroidX"); if (value != null) { return Boolean.parseBoolean(value); } return false; } private static VirtualFile getAndroidProjectDir(VirtualFile dir) { return (dir.findChild("app") == null) ? null : dir; } @Nullable private static VirtualFile getFlutterManagedAndroidDir(VirtualFile dir) { final VirtualFile meta = dir.findChild(".metadata"); if (meta != null) { try { final Properties properties = new Properties(); properties.load(new InputStreamReader(meta.getInputStream(), Charsets.UTF_8)); final String value = properties.getProperty("project_type"); if (value == null) { return null; } switch (value) { case "app": return dir.findChild("android"); case "module": return dir.findChild(".android"); case "package": return null; case "plugin": return dir.findFileByRelativePath("example/android"); } } catch (IOException e) { // fall thru } } VirtualFile android; android = dir.findChild(".android"); if (android != null) { return android; } android = dir.findChild("android"); if (android != null) { return android; } android = dir.findFileByRelativePath("example/android"); //noinspection RedundantIfStatement if (android != null) { return android; } return null; } @Nullable public static Module findModuleNamed(@NotNull Project project, @NotNull String name) { final Module[] modules = ModuleManager.getInstance(project).getModules(); for (Module module : modules) { if (module.getName().equals(name)) { return module; } } return null; } public static String flutterGradleModuleName(Project project) { return project.getName().replaceAll(" ", "_") + "." + AndroidUtils.FLUTTER_MODULE_NAME; } @Nullable public static Module findFlutterGradleModule(@NotNull Project project) { String moduleName = AndroidUtils.FLUTTER_MODULE_NAME; Module module = findModuleNamed(project, moduleName); if (module == null) { moduleName = flutterGradleModuleName(project); module = findModuleNamed(project, moduleName); if (module == null) { return null; } } VirtualFile file = locateModuleRoot(module); if (file == null) { return null; } file = file.getParent().getParent(); final VirtualFile meta = file.findChild(".metadata"); if (meta == null) { return null; } final VirtualFile android = getFlutterManagedAndroidDir(meta.getParent()); if (android != null && android.getName().equals(".android")) { return module; // Only true for Flutter modules. } return null; } @Nullable public static VirtualFile locateModuleRoot(@NotNull Module module) { final ModuleSourceOrderEntry entry = findModuleSourceEntry(module); if (entry == null) return null; final VirtualFile[] roots = entry.getRootModel().getContentRoots(); if (roots.length == 0) return null; return roots[0]; } @Nullable private static ModuleSourceOrderEntry findModuleSourceEntry(@NotNull Module module) { final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); final OrderEntry[] orderEntries = moduleRootManager.getOrderEntries(); for (OrderEntry entry : orderEntries) { if (entry instanceof ModuleSourceOrderEntry) { return (ModuleSourceOrderEntry)entry; } } return null; } @Nullable public static EmbeddedBrowser embeddedBrowser(Project project) { if (project == null || project.isDisposed()) { return null; } return FlutterSettings.getInstance().isEnableJcefBrowser() ? EmbeddedJcefBrowser.getInstance(project) : EmbeddedJxBrowser.getInstance(project); } public static boolean embeddedBrowserAvailable(JxBrowserStatus status) { return status.equals(JxBrowserStatus.INSTALLED) || status.equals(JxBrowserStatus.INSTALLATION_SKIPPED) && FlutterSettings.getInstance() .isEnableJcefBrowser(); } }
flutter-intellij/flutter-idea/src/io/flutter/FlutterUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/FlutterUtils.java", "repo_id": "flutter-intellij", "token_count": 7471 }
433
/* * 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.actions; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.pub.PubRoot; import org.jetbrains.annotations.NotNull; public class FlutterPackagesExplorerActionGroup extends DefaultActionGroup { private static boolean isFlutterPubspec(@NotNull AnActionEvent e) { final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(e.getDataContext()); final PubRoot root = file == null ? null : PubRoot.forDirectory(file.getParent()); return root != null && root.getPubspec().equals(file) && root.declaresFlutter(); } @Override public void update(@NotNull AnActionEvent e) { final boolean enabled = isFlutterPubspec(e); final Presentation presentation = e.getPresentation(); presentation.setEnabled(enabled); presentation.setVisible(enabled); } }
flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterPackagesExplorerActionGroup.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/FlutterPackagesExplorerActionGroup.java", "repo_id": "flutter-intellij", "token_count": 369 }
434
/* * 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.actions; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.FlutterConstants; import io.flutter.FlutterInitializer; import io.flutter.run.FlutterReloadManager; import io.flutter.run.daemon.FlutterApp; import org.jetbrains.annotations.NotNull; import java.awt.event.InputEvent; public class ReloadFlutterApp extends FlutterAppAction { public static final String ID = "Flutter.ReloadFlutterApp"; //NON-NLS public static final String TEXT = FlutterBundle.message("app.reload.action.text"); public static final String DESCRIPTION = FlutterBundle.message("app.reload.action.description"); public ReloadFlutterApp(@NotNull FlutterApp app, @NotNull Computable<Boolean> isApplicable) { super(app, TEXT, DESCRIPTION, FlutterIcons.HotReload, isApplicable, ID); // Shortcut is associated with toolbar action. copyShortcutFrom(ActionManager.getInstance().getAction("Flutter.Toolbar.ReloadAction")); } @Override public void actionPerformed(@NotNull AnActionEvent e) { final Project project = getEventProject(e); if (project == null) { return; } // If the shift key is held down, perform a restart. We check to see if we're being invoked from the // 'GoToAction' dialog. If so, the modifiers are for the command that opened the go to action dialog. final boolean shouldRestart = (e.getModifiers() & InputEvent.SHIFT_MASK) != 0 && !"GoToAction".equals(e.getPlace()); if (shouldRestart) { FlutterInitializer.sendAnalyticsAction(RestartFlutterApp.class.getSimpleName()); FlutterReloadManager.getInstance(project).saveAllAndRestart(getApp(), FlutterConstants.RELOAD_REASON_MANUAL); } else { // Else perform a hot reload. FlutterInitializer.sendAnalyticsAction(this); FlutterReloadManager.getInstance(project).saveAllAndReload(getApp(), FlutterConstants.RELOAD_REASON_MANUAL); } } // Override to disable the hot reload action when running flutter web apps. @Override public void update(@NotNull AnActionEvent e) { super.update(e); if (!getApp().appSupportsHotReload()) { e.getPresentation().setEnabled(false); } } }
flutter-intellij/flutter-idea/src/io/flutter/actions/ReloadFlutterApp.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/actions/ReloadFlutterApp.java", "repo_id": "flutter-intellij", "token_count": 834 }
435
/* * 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.analytics; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.openapi.wm.ex.ToolWindowManagerEx; import com.intellij.openapi.wm.ex.ToolWindowManagerListener; import org.jetbrains.annotations.NotNull; /** * This class interfaces with the IntelliJ tool window manager and reports tool window * usage to analytics. */ public class ToolWindowTracker implements ToolWindowManagerListener { public static void track(@NotNull Project project, @NotNull Analytics analytics) { new ToolWindowTracker(project, analytics); } private final Analytics myAnalytics; private final ToolWindowManagerEx myToolWindowManager; private String currentWindowId; private ToolWindowTracker(@NotNull Project project, @NotNull Analytics analytics) { myAnalytics = analytics; myToolWindowManager = ToolWindowManagerEx.getInstanceEx(project); project.getMessageBus().connect().subscribe(ToolWindowManagerListener.TOPIC, this); update(); } @Override public void stateChanged(@NotNull ToolWindowManager toolWindowManager) { update(); } private void update() { final String newWindow = findWindowId(); if (!StringUtil.equals(newWindow, currentWindowId)) { currentWindowId = newWindow; myAnalytics.sendScreenView(currentWindowId); } } @NotNull private String findWindowId() { final String newWindow = myToolWindowManager.getActiveToolWindowId(); return newWindow == null ? "editor" : newWindow.toLowerCase(); } }
flutter-intellij/flutter-idea/src/io/flutter/analytics/ToolWindowTracker.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/analytics/ToolWindowTracker.java", "repo_id": "flutter-intellij", "token_count": 522 }
436
/* * 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.dart; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.jetbrains.lang.dart.DartTokenTypes; import com.jetbrains.lang.dart.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Objects; import java.util.regex.Pattern; /** * Finds Dart PSI elements in IntelliJ's syntax tree. */ public class DartSyntax { /** * Finds the enclosing function call where the function being called has the given name. * <p> * Returns null if not found. */ @Nullable public static DartCallExpression findEnclosingFunctionCall(@NotNull PsiElement elt, @NotNull String functionName) { return findEnclosingFunctionCall(elt, functionName, new Equator<String, String>() { @Override boolean equate(@NotNull String first, @NotNull String second) { return Objects.equals(first, second); } }); } /** * Finds the enclosing function call where the function being called has a name matching {@param functionRegex}. * <p> * Returns null if not found. */ @Nullable public static DartCallExpression findEnclosingFunctionCall(@NotNull PsiElement elt, @NotNull Pattern functionRegex) { return findEnclosingFunctionCall(elt, functionRegex, new Equator<Pattern, String>() { @Override boolean equate(@NotNull Pattern first, @NotNull String second) { return first.matcher(second).matches(); } }); } private static <T> DartCallExpression findEnclosingFunctionCall( @NotNull PsiElement elt, @NotNull T functionDescriptor, @NotNull Equator<T, String> equator) { while (elt != null) { if (elt instanceof DartCallExpression) { final DartCallExpression call = (DartCallExpression)elt; final String name = getCalledFunctionName(call); if (name != null && equator.equate(functionDescriptor, name)) { return call; } } elt = elt.getParent(); } return null; // not found } /** * Finds the closest named function call that encloses {@param element}. */ @Nullable public static DartCallExpression findClosestEnclosingFunctionCall(@Nullable PsiElement element) { while (element != null) { if (element instanceof DartCallExpression) { final DartCallExpression call = (DartCallExpression)element; final String name = getCalledFunctionName(call); if (name != null) { return call; } } element = element.getParent(); } return null; // not found } @Nullable public static DartNewExpression findEnclosingNewExpression(@NotNull PsiElement elt) { while (elt != null) { if (elt instanceof DartNewExpression) { return (DartNewExpression)elt; } elt = elt.getParent(); } return null; } @Nullable public static DartReferenceExpression findEnclosingReferenceExpression(@NotNull PsiElement elt) { while (elt != null) { if (elt instanceof DartReferenceExpression) { if (!(elt.getParent() instanceof DartReferenceExpression)) { return (DartReferenceExpression)elt; } } elt = elt.getParent(); } return null; } /** * Gets an argument to a function call, provided that the expression has the given type. * <p> * Returns null if the argument doesn't exist or it's not the given type. */ @Nullable public static <E extends DartExpression> E getArgument(@NotNull DartCallExpression call, int index, @NotNull Class<E> expectedClass) { if (call.getArguments() == null) return null; final DartArgumentList list = call.getArguments().getArgumentList(); if (list == null) return null; final List<DartExpression> args = list.getExpressionList(); if (args.size() <= index) { return null; } try { return expectedClass.cast(args.get(index)); } catch (ClassCastException e) { return null; } } /** * Check if an element is a call to a function with the given {@param functionName}. * * @return true if the given element is a call to the function, false otherwise */ public static boolean isCallToFunctionNamed(@NotNull DartCallExpression element, @NotNull String functionName) { final String name = getCalledFunctionName(element); return Objects.equals(name, functionName); } /** * Check if an element is a call to a function matching the given {@param functionRegex}. * * @return true if the given element is a call to the function, false otherwise */ public static boolean isCallToFunctionMatching(@NotNull DartCallExpression element, @NotNull Pattern functionRegex) { final String name = getCalledFunctionName(element); return name != null && functionRegex.matcher(name).matches(); } /** * Check if an element is a declaration of "main". * * @return true if the given element is a main declaration, false otherwise */ public static boolean isMainFunctionDeclaration(@Nullable PsiElement element) { if (!(element instanceof DartFunctionDeclarationWithBodyOrNative)) { return false; } final String functionName = ((DartFunctionDeclarationWithBodyOrNative)element).getComponentName().getId().getText(); return Objects.equals(functionName, "main"); } /** * Returns the contents of a Dart string literal, provided that it doesn't do any interpolation. * <p> * Returns null if there is any string interpolation. */ @Nullable public static String unquote(@NotNull DartStringLiteralExpression lit) { if (!lit.getShortTemplateEntryList().isEmpty() || !lit.getLongTemplateEntryList().isEmpty()) { return null; // is a template } // We expect a quote, string part, quote. if (lit.getFirstChild() == null) return null; final PsiElement second = lit.getFirstChild().getNextSibling(); if (second.getNextSibling() != lit.getLastChild()) return null; // not three items if (!(second instanceof LeafPsiElement)) return null; final LeafPsiElement leaf = (LeafPsiElement)second; if (leaf.getElementType() != DartTokenTypes.REGULAR_STRING_PART) return null; return leaf.getText(); } @Nullable private static String getCalledFunctionName(@NotNull DartCallExpression call) { if (!(call.getFirstChild() instanceof DartReference)) return null; return call.getFirstChild().getText(); } /** * {@link java.util.Comparator}, but for equality checks. * * @param <T> * @param <S> */ private static abstract class Equator<T, S> { abstract boolean equate(@NotNull T first, @NotNull S second); } }
flutter-intellij/flutter-idea/src/io/flutter/dart/DartSyntax.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/dart/DartSyntax.java", "repo_id": "flutter-intellij", "token_count": 2338 }
437
/* * 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.editor; import com.intellij.openapi.diagnostic.Logger; import io.flutter.FlutterUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.awt.*; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class FlutterColors { private static final Logger LOG = Logger.getInstance(FlutterColors.class); public static class FlutterColor { @NotNull private final Color color; private final boolean isPrimary; FlutterColor(@NotNull Color color, boolean isPrimary) { this.color = color; this.isPrimary = isPrimary; } @NotNull public Color getAWTColor() { return color; } public boolean isPrimary() { return isPrimary; } } static final String primarySuffix = ".primary"; static final String defaultShade = "[500]"; private static final Properties colors; private static final Map<Color, String> colorToName; static { colors = new Properties(); try { colors.load(FlutterUtils.class.getResourceAsStream("/flutter/colors/material.properties")); } catch (IOException e) { FlutterUtils.warn(LOG, e); } colorToName = new HashMap<>(); for (Map.Entry<Object, Object> entry : colors.entrySet()) { final String name = (String)entry.getKey(); final String value = (String)entry.getValue(); final Color color = parseColor(value); if (color != null) { colorToName.put(color, name); } } } /** * @return the AWT color corresponding to the given Flutter color key. */ @Nullable public static FlutterColor getColor(@NotNull String key) { // Handle things like Colors.blue.shade200; convert the text to blue[200]. if (key.contains(".shade")) { key = key.replace(".shade", "[") + "]"; } if (colors.containsKey(key)) { final Color color = getColorValue(key); if (color != null) { return new FlutterColor(color, false); } } else if (colors.containsKey(key + primarySuffix)) { final Color color = getColorValue(key + primarySuffix); if (color != null) { return new FlutterColor(color, true); } } return null; } /** * Returns the the shortest material color name matching a color if one exists. */ @Nullable public static String getColorName(@Nullable Color color) { String name = colorToName.get(color); if (name == null) return null; // Normalize to avoid including suffixes that are not required. name = maybeTrimSuffix(name, primarySuffix); name = maybeTrimSuffix(name, defaultShade); return name; } private static String maybeTrimSuffix(String value, String suffix) { if (value.endsWith(suffix)) { return value.substring(0, value.length() - suffix.length()); } return value; } private static Color parseColor(String hexValue) { if (hexValue == null) { return null; } try { // argb to r, g, b, a final long value = Long.parseLong(hexValue, 16); //noinspection UseJBColor return new Color((int)(value >> 16) & 0xFF, (int)(value >> 8) & 0xFF, (int)value & 0xFF, (int)(value >> 24) & 0xFF); } catch (IllegalArgumentException e) { return null; } } private static Color getColorValue(String name) { final String hexValue = colors.getProperty(name); return parseColor(hexValue); } }
flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterColors.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/FlutterColors.java", "repo_id": "flutter-intellij", "token_count": 1335 }
438
/* * 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.editor; import com.intellij.openapi.actionSystem.*; 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.util.io.FileUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import com.intellij.ui.EditorNotifications; import icons.FlutterIcons; import io.flutter.FlutterBundle; import io.flutter.utils.UIUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; // TODO(devoncarew): Are we showing the 'Open in Xcode' editor action on non-mac platforms? public class NativeEditorNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> implements DumbAware { private static final Key<EditorNotificationPanel> KEY = Key.create("flutter.native.editor.notification"); private final Project project; private boolean showNotification = true; public NativeEditorNotificationProvider(@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 (!file.isInLocalFileSystem() || !showNotification) { return null; } return createPanelForFile(file, findRootDir(file, project.getBaseDir())); } private EditorNotificationPanel createPanelForFile(VirtualFile file, VirtualFile root) { if (root == null) { return null; } return createPanelForAction(file, root, getActionName(root)); } private EditorNotificationPanel createPanelForAction(VirtualFile file, VirtualFile root, String actionName) { if (actionName == null) { return null; } final NativeEditorActionsPanel panel = new NativeEditorActionsPanel(file, root, actionName); return panel.isValidForFile() ? panel : null; } private static String getActionName(VirtualFile root) { if (root == null) { return null; } if (root.getName().equals("android")) { return "flutter.androidstudio.open"; } else if (root.getName().equals("ios")) { return "flutter.xcode.open"; } else if (root.getName().equals("macos")) { return "flutter.xcode.open"; } else { return null; } } @Nullable private static VirtualFile findRootDir(@NotNull VirtualFile file, @Nullable VirtualFile projectDir) { if (projectDir == null) { return null; } // Return the top-most parent of file that is a child of the project directory. VirtualFile parent = file.getParent(); if (projectDir.equals(parent)) { return null; } VirtualFile root = parent; while (parent != null) { parent = parent.getParent(); if (projectDir.equals(parent)) { return root; } root = parent; } return null; } class NativeEditorActionsPanel extends EditorNotificationPanel { final VirtualFile myFile; final VirtualFile myRoot; final AnAction myAction; final boolean isVisible; NativeEditorActionsPanel(VirtualFile file, VirtualFile root, String actionName) { super(UIUtils.getEditorNotificationBackgroundColor()); myFile = file; myRoot = root; myAction = ActionManager.getInstance().getAction(actionName); icon(FlutterIcons.Flutter); text("Flutter commands"); // Ensure this project is a Flutter project by updating the menu action. It will only be visible for Flutter projects. myAction.update(AnActionEvent.createFromDataContext(ActionPlaces.EDITOR_TOOLBAR, myAction.getTemplatePresentation(), makeContext())); isVisible = myAction.getTemplatePresentation().isVisible(); createActionLabel(myAction.getTemplatePresentation().getText(), this::performAction) .setToolTipText(myAction.getTemplatePresentation().getDescription()); createActionLabel(FlutterBundle.message("flutter.androidstudio.open.hide.notification.text"), () -> { showNotification = false; EditorNotifications.getInstance(project).updateAllNotifications(); }).setToolTipText(FlutterBundle.message("flutter.androidstudio.open.hide.notification.description")); } private boolean isValidForFile() { if (isVisible) { // The menu items are visible for certain elements outside the module directories. return FileUtil.isAncestor(myRoot.getPath(), myFile.getPath(), true); } return false; } private void performAction() { // Open Xcode or Android Studio. If already running AS then just open a new window. myAction.actionPerformed( AnActionEvent.createFromDataContext(ActionPlaces.EDITOR_TOOLBAR, myAction.getTemplatePresentation(), makeContext())); } private DataContext makeContext() { return dataId -> { if (CommonDataKeys.VIRTUAL_FILE.is(dataId)) { return myFile; } if (CommonDataKeys.PROJECT.is(dataId)) { return project; } return null; }; } } }
flutter-intellij/flutter-idea/src/io/flutter/editor/NativeEditorNotificationProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/editor/NativeEditorNotificationProvider.java", "repo_id": "flutter-intellij", "token_count": 1973 }
439
/* * 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.font; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManagerListener; import org.jetbrains.annotations.NotNull; public class ProjectOpenListener implements ProjectManagerListener { //See https://plugins.jetbrains.com/docs/intellij/plugin-components.html#comintellijpoststartupactivity // for notice and documentation on the deprecation intentions of // Components from JetBrains. // // Migration forward has different directions before and after // 2023.1, if we can, it would be prudent to wait until we are // only supporting this major platform as a minimum version. // // https://github.com/flutter/flutter-intellij/issues/6953 @Override public void projectOpened(@NotNull Project project) { // Ensure this isn't part of testing if (ApplicationManager.getApplication().isUnitTestMode()) { return; } FontPreviewProcessor.analyze(project); } }
flutter-intellij/flutter-idea/src/io/flutter/font/ProjectOpenListener.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/font/ProjectOpenListener.java", "repo_id": "flutter-intellij", "token_count": 342 }
440
/* * 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.inspector; import io.flutter.inspector.InspectorService.ObjectGroup; import java.util.concurrent.CompletableFuture; /** * Manager that simplifies preventing memory leaks when using the * InspectorService. * <p> * This class is designed for the use case where you want to manage * object references associated with the current displayed UI and object * references associated with the candidate next frame of UI to display. Once * the next frame is ready, you determine whether you want to display it and * discard the current frame and promote the next frame to the the current * frame if you want to display the next frame otherwise you discard the next * frame. * <p> * To use this class load all data you want for the next frame by using * the object group specified by getNext() and then if you decide to switch * to display that frame, call promoteNext() otherwise call clearNext(). */ public class InspectorObjectGroupManager { private final InspectorService inspectorService; private final String debugName; private ObjectGroup current; private ObjectGroup next; private CompletableFuture<Void> pendingNextFuture; public InspectorService getInspectorService() { return inspectorService; } public InspectorObjectGroupManager(InspectorService inspectorService, String debugName) { this.inspectorService = inspectorService; this.debugName = debugName; } public CompletableFuture<?> getPendingUpdateDone() { if (pendingNextFuture != null) { return pendingNextFuture; } if (next == null) { // There is no pending update. return CompletableFuture.completedFuture(null); } pendingNextFuture = new CompletableFuture<>(); return pendingNextFuture; } public ObjectGroup getCurrent() { if (current == null) { current = inspectorService.createObjectGroup(debugName); } return current; } public ObjectGroup getNext() { if (next == null) { next = inspectorService.createObjectGroup(debugName); } return next; } public void clear(boolean isolateStopped) { if (isolateStopped) { // The Dart VM will handle GCing the underlying memory. current = null; setNextNull(); } else { clearCurrent(); cancelNext(); } } public void promoteNext() { clearCurrent(); current = next; setNextNull(); } private void clearCurrent() { if (current != null) { current.dispose(); current = null; } } public void cancelNext() { if (next != null) { next.dispose(); setNextNull(); } } private void setNextNull() { next = null; if (pendingNextFuture != null) { pendingNextFuture.complete(null); pendingNextFuture = null; } } }
flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorObjectGroupManager.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/inspector/InspectorObjectGroupManager.java", "repo_id": "flutter-intellij", "token_count": 917 }
441
package io.flutter.jxbrowser; public class InstallationFailedReason { public FailureType failureType; public String detail; public InstallationFailedReason(FailureType failureType) { this(failureType, null); } InstallationFailedReason(FailureType failureType, String detail) { this.failureType = failureType; this.detail = detail; } }
flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/InstallationFailedReason.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/jxbrowser/InstallationFailedReason.java", "repo_id": "flutter-intellij", "token_count": 131 }
442
/* * 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.module.settings; import com.intellij.openapi.ui.ComboBox; import io.flutter.FlutterBundle; import io.flutter.FlutterUtils; import io.flutter.module.FlutterProjectType; import io.flutter.sdk.FlutterSdk; import io.flutter.sdk.FlutterSdkVersion; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.function.Supplier; public class ProjectType { private static final class ProjectTypeComboBoxModel extends AbstractListModel<FlutterProjectType> implements ComboBoxModel<FlutterProjectType> { private final List<FlutterProjectType> myList = new ArrayList<>(EnumSet.allOf(FlutterProjectType.class)); private FlutterProjectType mySelected; private ProjectTypeComboBoxModel() { if (System.getProperty("flutter.experimental.modules", null) == null) { if (!FlutterUtils.isAndroidStudio()) { myList.remove(FlutterProjectType.MODULE); } myList.remove(FlutterProjectType.IMPORT); } mySelected = myList.get(0); } @Override public int getSize() { return myList.size(); } @Override public FlutterProjectType getElementAt(int index) { return myList.get(index); } @Override public void setSelectedItem(Object item) { setSelectedItem((FlutterProjectType)item); } @Override public FlutterProjectType getSelectedItem() { return mySelected; } public void setSelectedItem(FlutterProjectType item) { mySelected = item; fireContentsChanged(this, 0, getSize()); } void addSkeleton() { if (!myList.contains(FlutterProjectType.SKELETON)) { myList.add(FlutterProjectType.SKELETON); } } void removeSkeleton() { myList.remove(FlutterProjectType.SKELETON); } void addPluginFfi() { if (!myList.contains(FlutterProjectType.PLUGIN_FFI)) { myList.add(FlutterProjectType.PLUGIN_FFI); } } void removePluginFfi() { myList.remove(FlutterProjectType.PLUGIN_FFI); } void addEmptyProject() { if (!myList.contains(FlutterProjectType.EMPTY_PROJECT)) { myList.add(FlutterProjectType.EMPTY_PROJECT); } } void removeEmptyProject() { myList.remove(FlutterProjectType.EMPTY_PROJECT); } } private Supplier<? extends FlutterSdk> getSdk; private JPanel projectTypePanel; private ComboBox<FlutterProjectType> projectTypeCombo; public ProjectType(@Nullable Supplier<? extends FlutterSdk> getSdk) { this.getSdk = getSdk; } @SuppressWarnings("unused") public ProjectType() { // Required by AS NPW } private void createUIComponents() { projectTypeCombo = new ComboBox<>(); projectTypeCombo.setModel(new ProjectTypeComboBoxModel()); projectTypeCombo.setToolTipText(FlutterBundle.message("flutter.module.create.settings.type.tip")); } @NotNull public JComponent getComponent() { return projectTypePanel; } public FlutterProjectType getType() { return (FlutterProjectType)projectTypeCombo.getSelectedItem(); } public ComboBox<FlutterProjectType> getProjectTypeCombo() { return projectTypeCombo; } public void setSdk(@NotNull Supplier<? extends FlutterSdk> sdk) { this.getSdk = sdk; } public void addListener(ItemListener listener) { projectTypeCombo.addItemListener(listener); } public void updateProjectTypes() { FlutterSdkVersion version = getSdk.get().getVersion(); ProjectTypeComboBoxModel model = (ProjectTypeComboBoxModel)projectTypeCombo.getModel(); if (version.isSkeletonTemplateAvailable()) { model.addSkeleton(); } else { model.removeSkeleton(); } if (version.isPluginFfiTemplateAvailable()) { model.addPluginFfi(); } else { model.removePluginFfi(); } if (version.isEmptyProjectAvailable()) { model.addEmptyProject(); } else { model.removeEmptyProject(); } } }
flutter-intellij/flutter-idea/src/io/flutter/module/settings/ProjectType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/module/settings/ProjectType.java", "repo_id": "flutter-intellij", "token_count": 1594 }
443
/* * 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; /** * Performance metrics. * <p> * Additional performance metrics can be defined without requiring changes to * package:flutter as computation of metrics is performed in Java using * the SlidingWindowStats class. */ public enum PerfMetric { lastFrame("Last Frame", true), peakRecent("Peak Recent", true), pastSecond("Past Second", true), totalSinceEnteringCurrentScreen("Current Screen", false), total("Total", false); public final String name; public final boolean timeIntervalMetric; PerfMetric(String name, boolean timeIntervalMetric) { this.name = name; this.timeIntervalMetric = timeIntervalMetric; } @Override public String toString() { return name; } }
flutter-intellij/flutter-idea/src/io/flutter/perf/PerfMetric.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/perf/PerfMetric.java", "repo_id": "flutter-intellij", "token_count": 258 }
444
/* * 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.performance; import com.intellij.ide.util.PropertiesComponent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowFactory; import com.intellij.openapi.wm.ToolWindowManager; import io.flutter.utils.ViewListener; import io.flutter.view.FlutterViewMessages; import org.jetbrains.annotations.NotNull; public class FlutterPerformanceViewFactory implements ToolWindowFactory, DumbAware { private static final String TOOL_WINDOW_VISIBLE_PROPERTY = "flutter.performance.tool.window.visible"; public static void init(@NotNull Project project) { project.getMessageBus().connect().subscribe( FlutterViewMessages.FLUTTER_DEBUG_TOPIC, (event) -> initPerfView(project, event) ); final ToolWindow window = ToolWindowManager.getInstance(project).getToolWindow(FlutterPerformanceView.TOOL_WINDOW_ID); if (window != null) { window.setAvailable(true); if (PropertiesComponent.getInstance(project).getBoolean(TOOL_WINDOW_VISIBLE_PROPERTY, false)) { window.activate(null, false); } } } private static void initPerfView(@NotNull Project project, FlutterViewMessages.FlutterDebugEvent event) { ApplicationManager.getApplication().invokeLater(() -> { final FlutterPerformanceView flutterPerfView = project.getService(FlutterPerformanceView.class); ToolWindowManager.getInstance(project).getToolWindow(FlutterPerformanceView.TOOL_WINDOW_ID).setAvailable(true); flutterPerfView.debugActive(event); }); } @Override public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { //noinspection CodeBlock2Expr DumbService.getInstance(project).runWhenSmart(() -> { (project.getService(FlutterPerformanceView.class)).initToolWindow(toolWindow); }); } @Override public boolean shouldBeAvailable(@NotNull Project project) { return false; } public static class FlutterPerformanceViewListener extends ViewListener { public FlutterPerformanceViewListener(@NotNull Project project) { super(project, FlutterPerformanceView.TOOL_WINDOW_ID, TOOL_WINDOW_VISIBLE_PROPERTY); } } }
flutter-intellij/flutter-idea/src/io/flutter/performance/FlutterPerformanceViewFactory.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/performance/FlutterPerformanceViewFactory.java", "repo_id": "flutter-intellij", "token_count": 809 }
445
/* * 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.project; import com.intellij.icons.AllIcons; import com.intellij.ide.IconProvider; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable.IconFlags; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.ui.LayeredIcon; import com.jetbrains.lang.dart.DartFileType; import com.jetbrains.lang.dart.psi.DartFile; import icons.FlutterIcons; import io.flutter.FlutterUtils; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRootCache; import io.flutter.utils.FlutterModuleUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Objects; public class FlutterIconProvider extends IconProvider { private static final Icon TEST_FILE = overlayIcons(DartFileType.INSTANCE.getIcon(), AllIcons.Nodes.JunitTestMark); @Nullable public Icon getIcon(@NotNull PsiElement element, @IconFlags int flags) { final Project project = element.getProject(); if (!FlutterModuleUtils.declaresFlutter(project)) return null; // Directories. if (element instanceof PsiDirectory) { final VirtualFile dir = ((PsiDirectory)element).getVirtualFile(); if (!dir.isInLocalFileSystem()) return null; final PubRootCache pubRootCache = PubRootCache.getInstance(project); // Show an icon for flutter modules. final PubRoot pubRoot = pubRootCache.getRoot(dir); if (pubRoot != null && dir.equals(pubRoot.getRoot()) && pubRoot.declaresFlutter()) { return FlutterIcons.Flutter; } final PubRoot root = pubRootCache.getRoot(dir.getParent()); if (root == null) return null; // TODO(devoncarew): should we just make the folder a source kind? if (dir.equals(root.getLib())) return AllIcons.Modules.SourceRoot; if (Objects.equals(dir, root.getAndroidDir())) return AllIcons.Nodes.KeymapTools; if (Objects.equals(dir, root.getiOsDir())) return AllIcons.Nodes.KeymapTools; if (Objects.equals(dir, root.getIntegrationTestDir())) return AllIcons.Nodes.TestSourceFolder; if (dir.isDirectory() && dir.getName().equals(".idea")) return AllIcons.Modules.GeneratedFolder; } // Files. if (element instanceof DartFile) { final DartFile dartFile = (DartFile)element; final VirtualFile file = dartFile.getVirtualFile(); if (file == null || !file.isInLocalFileSystem()) return null; // Use a simple naming convention heuristic to identify test files. // TODO(pq): consider pushing up to the Dart Plugin. if (FlutterUtils.isInTestDir(dartFile) && file.getName().endsWith("_test.dart")) { return TEST_FILE; } } return null; } @NotNull private static Icon overlayIcons(@NotNull Icon... icons) { final LayeredIcon result = new LayeredIcon(icons.length); for (int layer = 0; layer < icons.length; layer++) { result.setIcon(icons[layer], layer); } return result; } }
flutter-intellij/flutter-idea/src/io/flutter/project/FlutterIconProvider.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/project/FlutterIconProvider.java", "repo_id": "flutter-intellij", "token_count": 1147 }
446
/* * 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.google.common.annotations.VisibleForTesting; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.search.GlobalSearchScopesCore; import com.intellij.util.PathUtil; import com.intellij.xdebugger.XSourcePosition; import com.jetbrains.lang.dart.analyzer.DartAnalysisServerService; import com.jetbrains.lang.dart.util.DartResolveUtil; import com.jetbrains.lang.dart.util.DartUrlResolver; import gnu.trove.THashMap; import io.flutter.FlutterInitializer; import io.flutter.FlutterUtils; import io.flutter.analytics.Analytics; import io.flutter.bazel.WorkspaceCache; import io.flutter.dart.DartPlugin; import io.flutter.vmService.DartVmServiceDebugProcess; import org.dartlang.vm.service.element.LibraryRef; import org.dartlang.vm.service.element.Script; import org.dartlang.vm.service.element.ScriptRef; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; /** * Converts positions between Dart files in Observatory and local Dart files. * <p> * Used when setting breakpoints, stepping through code, and so on while debugging. */ public class FlutterPositionMapper implements DartVmServiceDebugProcess.PositionMapper { private static final Logger LOG = Logger.getInstance(FlutterPositionMapper.class); @NotNull private final Project project; /** * The directory containing the Flutter application's source code. * <p> * For pub-based projects, this should be the directory containing pubspec.yaml. */ @NotNull private final VirtualFile sourceRoot; @NotNull private final DartUrlResolver resolver; /** * Used to ask the Dart analysis server to convert between Dart URI's and local absolute paths. */ @Nullable private final Analyzer analyzer; /** * Callback to download a Dart file from Observatory. * <p> * Initialized when the debugger connects. */ @Nullable private DartVmServiceDebugProcess.ScriptProvider scriptProvider; /** * The "devfs" base uri reported by the flutter process on startup. * <p> * Initialized when the debugger connects. */ @Nullable private String remoteBaseUri; /** * A prefix to be removed from a remote path before looking for a corresponding file under the local source root. * <p> * Initialized shortly after connecting. */ @Nullable private String remoteSourceRoot; // TODO(skybrian) clear the cache at hot restart? (Old cache entries seem unlikely to be used again.) /** * A cache containing each file version downloaded from Observatory. The key is an isolate id. */ private final Map<String, ObservatoryFile.Cache> fileCache = new THashMap<>(); public FlutterPositionMapper(@NotNull Project project, @NotNull VirtualFile sourceRoot, @NotNull DartUrlResolver resolver, @Nullable Analyzer analyzer) { this.project = project; this.sourceRoot = sourceRoot; this.resolver = resolver; this.analyzer = analyzer; } @NotNull public Project getProject() { return project; } public void onConnect(@NotNull DartVmServiceDebugProcess.ScriptProvider provider, @Nullable String remoteBaseUri) { if (this.scriptProvider != null) { throw new IllegalStateException("already connected"); } this.scriptProvider = provider; this.remoteBaseUri = remoteBaseUri; } /** * Just after connecting, the debugger downloads the list of Dart libraries from Observatory and reports it here. */ public void onLibrariesDownloaded(@NotNull final Iterable<LibraryRef> libraries) { // TODO(skybrian) what should we do if this gets called multiple times? // This happens when there is more than one isolate. // Currently it overwrites the previous value. // Calculate the remote source root. for (LibraryRef library : libraries) { final String remoteUri = library.getUri(); if (remoteUri.startsWith(DartUrlResolver.DART_PREFIX)) continue; if (remoteUri.startsWith(DartUrlResolver.PACKAGE_PREFIX)) continue; remoteSourceRoot = findRemoteSourceRoot(remoteUri); if (remoteSourceRoot != null) return; } } /** * Attempts to find a directory in Observatory corresponding to the local sourceRoot. * <p> * The strategy is to find a matching local file (under sourceRoot), and remove the common suffix. * <p> * Returns null if there isn't a unique result. */ private String findRemoteSourceRoot(String remotePath) { // Find files with the same filename (matching the suffix after the last slash). final PsiFile[] localFilesWithSameName = ApplicationManager.getApplication().runReadAction((Computable<PsiFile[]>)() -> { final String remoteFileName = PathUtil.getFileName(remotePath); final GlobalSearchScope scope = GlobalSearchScopesCore.directoryScope(project, sourceRoot, true); return FilenameIndex.getFilesByName(project, remoteFileName, scope); }); String match = null; for (PsiFile psiFile : localFilesWithSameName) { final VirtualFile local = DartResolveUtil.getRealVirtualFile(psiFile); if (local == null) continue; assert local.getPath().startsWith(sourceRoot.getPath() + "/"); final String relativeLocal = local.getPath().substring(sourceRoot.getPath().length()); // starts with slash if (remotePath.endsWith(relativeLocal)) { if (match != null) { return null; // found multiple matches } match = remotePath.substring(0, remotePath.length() - relativeLocal.length()); } } return match; } /** * Returns all possible Observatory URI's corresponding to a local file. * <p> * We don't know where the file will be so we set breakpoints in a lot of places. * (The URI may change after a hot restart.) */ @NotNull public Collection<String> getBreakpointUris(@NotNull final VirtualFile file) { final Set<String> results = new HashSet<>(); final String uriByIde = resolver.getDartUrlForFile(file); // If dart:, short circuit the results. if (uriByIde.startsWith(DartUrlResolver.DART_PREFIX)) { results.add(uriByIde); return results; } // file: if (uriByIde.startsWith(DartUrlResolver.FILE_PREFIX)) { results.add(threeSlashize(uriByIde)); } else { results.add(uriByIde); results.add(threeSlashize(new File(file.getPath()).toURI().toString())); } if (WorkspaceCache.getInstance(project).isBazel()) { FlutterInitializer.getAnalytics().sendEvent("breakpoint", analyzer == null ? "analyzer-found" : "analyzer-null"); } // package: (if applicable) if (analyzer != null) { final String uriByServer = analyzer.getUri(file.getPath()); if (uriByServer != null) { results.add(uriByServer); } } final String path = file.getPath(); final String root = sourceRoot.getPath(); if (path.startsWith(root)) { // snapshot prefix (if applicable) if (remoteSourceRoot != null) { results.add(remoteSourceRoot + path.substring(root.length())); } // remote prefix (if applicable) if (remoteBaseUri != null) { results.add(remoteBaseUri + path.substring(root.length())); } } return results; } /** * Returns the local position (to display to the user) corresponding to a token position in Observatory. */ @Nullable public XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final ScriptRef scriptRef, int tokenPos, CompletableFuture<String> fileFuture) { return getSourcePosition(isolateId, scriptRef.getId(), scriptRef.getUri(), tokenPos, fileFuture); } /** * Returns the local position (to display to the user) corresponding to a token position in Observatory. */ @Nullable public XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final Script script, int tokenPos) { return getSourcePosition(isolateId, script.getId(), script.getUri(), tokenPos); } private XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final String scriptId, @NotNull final String scriptUri, int tokenPos) { return getSourcePosition(isolateId, scriptId, scriptUri, tokenPos, null); } /** * Returns the local position (to display to the user) corresponding to a token position in Observatory. */ @Nullable private XSourcePosition getSourcePosition(@NotNull final String isolateId, @NotNull final String scriptId, @NotNull final String scriptUri, int tokenPos, CompletableFuture<String> fileFuture) { if (scriptProvider == null) { FlutterUtils.warn(LOG, "attempted to get source position before connected to observatory"); return null; } final VirtualFile local = findLocalFile(scriptUri, fileFuture); final ObservatoryFile.Cache cache = fileCache.computeIfAbsent(isolateId, (id) -> new ObservatoryFile.Cache(id, scriptProvider)); final ObservatoryFile remote = cache.downloadOrGet(scriptId, local == null); if (remote == null) return null; return remote.createPosition(local, tokenPos); } @VisibleForTesting @Nullable String getRemoteSourceRoot() { return remoteSourceRoot; } /** * Attempt to find a local Dart file corresponding to a script in Observatory. */ @Nullable private VirtualFile findLocalFile(@NotNull ScriptRef scriptRef) { return findLocalFile(scriptRef.getUri()); } /** * Attempt to find a local Dart file corresponding to a script in Observatory. */ @Nullable private VirtualFile findLocalFile(@NotNull Script script) { return findLocalFile(script.getUri()); } @Nullable protected VirtualFile findLocalFile(@NotNull String uri) { return findLocalFile(uri, null); } /** * Attempt to find a local Dart file corresponding to a script in Observatory. */ @Nullable protected VirtualFile findLocalFile(@NotNull String uri, CompletableFuture<String> fileFuture) { return ApplicationManager.getApplication().runReadAction((Computable<VirtualFile>)() -> { // This can be a remote file or URI. if (remoteSourceRoot != null && uri.startsWith(remoteSourceRoot)) { final String rootUri = StringUtil.trimEnd(resolver.getDartUrlForFile(sourceRoot), '/'); final String suffix = uri.substring(remoteSourceRoot.length()); return resolver.findFileByDartUrl(rootUri + suffix); } if (remoteBaseUri != null && uri.startsWith(remoteBaseUri)) { final String rootUri = StringUtil.trimEnd(resolver.getDartUrlForFile(sourceRoot), '/'); final String suffix = uri.substring(remoteBaseUri.length()); return resolver.findFileByDartUrl(rootUri + suffix); } final String remoteUri; if (uri.startsWith("/")) { // Convert a file path to a file: uri. remoteUri = new File(uri).toURI().toString(); } else { remoteUri = uri; } // See if the analysis server can resolve the URI. if (analyzer != null && !isDartPatchUri(remoteUri)) { final String path = analyzer.getAbsolutePath(remoteUri); if (path != null) { if (fileFuture != null && WorkspaceCache.getInstance(project).isBazel() && path.contains("google3")) { // Check if this path matches file future final Analytics analytics = FlutterInitializer.getAnalytics(); try { final String vmServiceFilePath = fileFuture.get(1000, TimeUnit.MILLISECONDS); if (!path.equals(vmServiceFilePath)) { analytics.sendEvent("file-mapping", String.format("mismatch|%s|%s", path, vmServiceFilePath)); } } catch (Exception e) { analytics.sendEvent("file-mapping", String.format("exception|%s|%s", path, e.getMessage())); } } return LocalFileSystem.getInstance().findFileByPath(path); } } // Otherwise, assume no mapping is needed and see if we can resolve it locally. return resolver.findFileByDartUrl(remoteUri); }); } @NotNull private static String threeSlashize(@NotNull final String uri) { if (!uri.startsWith("file:")) return uri; if (uri.startsWith("file:///")) return uri; if (uri.startsWith("file://")) return "file:///" + uri.substring("file://".length()); if (uri.startsWith("file:/")) return "file:///" + uri.substring("file:/".length()); if (uri.startsWith("file:")) return "file:///" + uri.substring("file:".length()); return uri; } private static boolean isDartPatchUri(@NotNull final String uri) { // dart:_builtin or dart:core-patch/core_patch.dart return uri.startsWith("dart:_") || uri.startsWith("dart:") && uri.contains("-patch/"); } public void shutdown() { if (analyzer != null) { analyzer.close(); } } /** * Wraps a Dart analysis server and execution id for doing URI resolution for a particular Flutter app. * <p> * (Can be mocked out for unit tests.) */ public interface Analyzer { @Nullable String getAbsolutePath(@NotNull String dartUri); @Nullable String getUri(@NotNull String absolutePath); void close(); /** * Sets up the analysis server to resolve URI's for a Flutter app, if possible. * * @param sourceLocation the file containing the app's main() method, or a directory containing it. */ @Nullable static Analyzer create(@NotNull Project project, @NotNull VirtualFile sourceLocation) { final DartAnalysisServerService service = DartPlugin.getInstance().getAnalysisService(project); if (!service.serverReadyForRequest()) { // TODO(skybrian) make this required to debug at all? It seems bad for breakpoints to be flaky. FlutterUtils.warn(LOG, "Dart analysis server is not running. Some breakpoints may not work."); return null; } final String contextId = service.execution_createContext(sourceLocation.getPath()); if (contextId == null) { FlutterUtils.warn(LOG, "Failed to get execution context from analysis server. Some breakpoints may not work."); return null; } return new Analyzer() { @Override @Nullable public String getAbsolutePath(@NotNull String dartUri) { return service.execution_mapUri(contextId, null, dartUri); } @Override @Nullable public String getUri(@NotNull String absolutePath) { return service.execution_mapUri(contextId, absolutePath, null); } @Override public void close() { service.execution_deleteContext(contextId); } }; } } }
flutter-intellij/flutter-idea/src/io/flutter/run/FlutterPositionMapper.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/FlutterPositionMapper.java", "repo_id": "flutter-intellij", "token_count": 5490 }
447
/* * 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.run.bazel; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; import com.intellij.execution.configurations.*; import com.intellij.execution.runners.ExecutionEnvironment; import com.intellij.execution.runners.RunConfigurationWithSuppressedDefaultRunAction; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtil; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.WriteExternalException; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import io.flutter.bazel.Workspace; import io.flutter.run.FlutterDevice; import io.flutter.run.LaunchState; import io.flutter.run.common.RunMode; import io.flutter.run.daemon.FlutterApp; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class BazelRunConfig extends RunConfigurationBase<LaunchState> implements RunConfigurationWithSuppressedDefaultRunAction, LaunchState.RunConfig { @NotNull protected BazelFields fields; BazelRunConfig(final @NotNull Project project, final @NotNull ConfigurationFactory factory, @NotNull final String name) { super(project, factory, name); fields = new BazelFields(null, null, null, false); } @NotNull BazelFields getFields() { return fields; } void setFields(@NotNull BazelFields newFields) { fields = newFields; } @Override public void checkConfiguration() throws RuntimeConfigurationException { fields.checkRunnable(getProject()); } @NotNull @Override public SettingsEditor<? extends RunConfiguration> getConfigurationEditor() { return new FlutterBazelConfigurationEditorForm(getProject()); } @NotNull @Override public LaunchState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment env) throws ExecutionException { final BazelFields launchFields = fields.copy(); try { launchFields.checkRunnable(env.getProject()); } catch (RuntimeConfigurationError e) { throw new ExecutionException(e); } final Workspace workspace = fields.getWorkspace(getProject()); final VirtualFile workspaceRoot = workspace.getRoot(); final RunMode mode = RunMode.fromEnv(env); final Module module = ModuleUtil.findModuleForFile(workspaceRoot, env.getProject()); final LaunchState.CreateAppCallback createAppCallback = (@Nullable FlutterDevice device) -> { if (device == null) return null; final GeneralCommandLine command = getCommand(env, device); return FlutterApp.start(env, env.getProject(), module, mode, device, command, StringUtil.capitalize(mode.mode()) + "BazelApp", "StopBazelApp"); }; return new LaunchState(env, workspaceRoot, workspaceRoot, this, createAppCallback); } @NotNull @Override public GeneralCommandLine getCommand(ExecutionEnvironment env, @NotNull FlutterDevice device) throws ExecutionException { final BazelFields launchFields = fields.copy(); final RunMode mode = RunMode.fromEnv(env); return launchFields.getLaunchCommand(env.getProject(), device, mode); } public BazelRunConfig clone() { final BazelRunConfig clone = (BazelRunConfig)super.clone(); clone.fields = fields.copy(); return clone; } RunConfiguration copyTemplateToNonTemplate(String name) { final BazelRunConfig copy = (BazelRunConfig)super.clone(); copy.setName(name); copy.fields = fields.copy(); return copy; } @Override public void writeExternal(@NotNull final Element element) throws WriteExternalException { super.writeExternal(element); fields.writeTo(element); } @Override public void readExternal(@NotNull final Element element) throws InvalidDataException { super.readExternal(element); fields = BazelFields.readFrom(element); } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelRunConfig.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazel/BazelRunConfig.java", "repo_id": "flutter-intellij", "token_count": 1306 }
448
/* * 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.psi.PsiElement; import io.flutter.run.common.TestLineMarkerContributor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * Annotates bazel Flutter tests with line markers. */ public class FlutterBazelTestLineMarkerContributor extends TestLineMarkerContributor { public FlutterBazelTestLineMarkerContributor() { super(BazelTestConfigUtils.getInstance()); } @Nullable @Override public Info getInfo(@NotNull PsiElement element) { return super.getInfo(element); } }
flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestLineMarkerContributor.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/bazelTest/FlutterBazelTestLineMarkerContributor.java", "repo_id": "flutter-intellij", "token_count": 236 }
449
/* * 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.run.daemon; public class DevToolsInstance { final public String host; final public int port; public DevToolsInstance(String host, int port) { this.host = host; this.port = port; } }
flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DevToolsInstance.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/daemon/DevToolsInstance.java", "repo_id": "flutter-intellij", "token_count": 118 }
450
/* * 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.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; /** * A debug process used when debugging a Flutter test. */ public class TestDebugProcess extends DartVmServiceDebugProcess { @NotNull private final ObservatoryConnector connector; public TestDebugProcess(@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/test/TestDebugProcess.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/run/test/TestDebugProcess.java", "repo_id": "flutter-intellij", "token_count": 714 }
451
/* * 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.sdk; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.libraries.LibraryType; import com.intellij.openapi.roots.libraries.NewLibraryConfiguration; import com.intellij.openapi.roots.libraries.PersistentLibraryKind; import com.intellij.openapi.roots.libraries.ui.LibraryEditorComponent; import com.intellij.openapi.roots.libraries.ui.LibraryPropertiesEditor; import com.intellij.openapi.vfs.VirtualFile; import icons.FlutterIcons; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; public class FlutterPluginLibraryType extends LibraryType<FlutterPluginLibraryProperties> { public static final String FLUTTER_PLUGINS_LIBRARY_NAME = "Flutter Plugins"; public static final PersistentLibraryKind<FlutterPluginLibraryProperties> LIBRARY_KIND = new PersistentLibraryKind<FlutterPluginLibraryProperties>("FlutterPluginsLibraryType") { @Override @NotNull public FlutterPluginLibraryProperties createDefaultProperties() { return new FlutterPluginLibraryProperties(); } }; protected FlutterPluginLibraryType() { super(LIBRARY_KIND); } @Nullable @Override public String getCreateActionName() { return null; } @Nullable @Override public NewLibraryConfiguration createNewLibrary(@NotNull JComponent component, @Nullable VirtualFile file, @NotNull Project project) { return null; } @Nullable @Override public LibraryPropertiesEditor createPropertiesEditor(@NotNull LibraryEditorComponent<FlutterPluginLibraryProperties> component) { return null; } @Nullable public Icon getIcon(@Nullable FlutterPluginLibraryProperties properties) { return FlutterIcons.Flutter; } }
flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginLibraryType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/sdk/FlutterPluginLibraryType.java", "repo_id": "flutter-intellij", "token_count": 597 }
452
/* * 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.template; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.lang.dart.ide.template.DartTemplateContextType; import com.jetbrains.lang.dart.psi.DartClassDefinition; import org.jetbrains.annotations.NotNull; public class DartToplevelTemplateContextType extends DartTemplateContextType { public DartToplevelTemplateContextType() { super("DART_TOPLEVEL", "Top-level", Generic.class); } @Override protected boolean isInContext(@NotNull PsiElement element) { return PsiTreeUtil.getNonStrictParentOfType(element, DartClassDefinition.class, PsiComment.class) == null; } }
flutter-intellij/flutter-idea/src/io/flutter/template/DartToplevelTemplateContextType.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/template/DartToplevelTemplateContextType.java", "repo_id": "flutter-intellij", "token_count": 278 }
453
/* * 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 com.intellij.execution.RunManager; import com.intellij.execution.RunnerAndConfigurationSettings; import com.intellij.facet.Facet; import com.intellij.facet.FacetManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.*; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.serviceContainer.AlreadyDisposedException; import com.intellij.ui.EditorNotifications; import com.intellij.util.PlatformUtils; import com.jetbrains.lang.dart.DartFileType; import com.jetbrains.lang.dart.sdk.DartSdk; import com.jetbrains.lang.dart.util.PubspecYamlUtil; import io.flutter.FlutterUtils; import io.flutter.actions.FlutterBuildActionGroup; import io.flutter.bazel.Workspace; import io.flutter.bazel.WorkspaceCache; import io.flutter.dart.DartPlugin; import io.flutter.pub.PubRoot; import io.flutter.pub.PubRootCache; import io.flutter.pub.PubRoots; import io.flutter.run.FlutterRunConfigurationType; import io.flutter.run.SdkFields; import io.flutter.run.SdkRunConfig; import io.flutter.sdk.FlutterSdk; import io.flutter.sdk.FlutterSdkUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class FlutterModuleUtils { public static final String DEPRECATED_FLUTTER_MODULE_TYPE_ID = "WEB_MODULE"; private FlutterModuleUtils() { } /** * This provides the {@link ModuleType} ID for Flutter modules to be assigned by the {@link io.flutter.module.FlutterModuleBuilder} and * elsewhere in the Flutter plugin. * <p/> * For Flutter module detection however, {@link ModuleType}s should not be used to determine Flutterness. */ @SuppressWarnings("SameReturnValue") @NotNull public static String getModuleTypeIDForFlutter() { return "JAVA_MODULE"; } public static ModuleType<?> getFlutterModuleType() { return ModuleTypeManager.getInstance().findByID(getModuleTypeIDForFlutter()); } /** * Return true if the passed module is of a Flutter type. Before version M16 this plugin had its own Flutter {@link ModuleType}. * Post M16 a Flutter module is defined by the following: * <p> * <code> * [Flutter support enabled for a module] === * [Dart support enabled && referenced Dart SDK is the one inside a Flutter SDK] * </code> */ public static boolean isFlutterModule(@Nullable final Module module) { if (module == null || module.isDisposed()) return false; if (PlatformUtils.isIntelliJ() || FlutterUtils.isAndroidStudio()) { // [Flutter support enabled for a module] === // [Dart support enabled && referenced Dart SDK is the one inside a Flutter SDK] final DartSdk dartSdk = DartPlugin.getDartSdk(module.getProject()); final String dartSdkPath = dartSdk != null ? dartSdk.getHomePath() : null; return validDartSdkPath(dartSdkPath) && DartPlugin.isDartSdkEnabled(module); } else { // If not IntelliJ, assume a small IDE (no multi-module project support). return declaresFlutter(module); } } private static boolean validDartSdkPath(String path) { return path != null && (path.endsWith(FlutterSdk.DART_SDK_SUFFIX) || path.endsWith(FlutterSdk.LINUX_DART_SUFFIX) || path.endsWith(FlutterSdk.LOCAL_DART_SUFFIX) || path.endsWith(FlutterSdk.MAC_DART_SUFFIX)); } public static boolean hasInternalDartSdkPath(Project project) { final DartSdk dartSdk = DartPlugin.getDartSdk(project); final String dartSdkPath = dartSdk != null ? dartSdk.getHomePath() : ""; return dartSdkPath.endsWith(FlutterSdk.LINUX_DART_SUFFIX) || dartSdkPath.endsWith(FlutterSdk.MAC_DART_SUFFIX); } public static boolean hasFlutterModule(@NotNull Project project) { if (project.isDisposed()) return false; return CollectionUtils.anyMatch(getModules(project), FlutterModuleUtils::isFlutterModule); } public static boolean isInFlutterModule(@NotNull PsiElement element) { return isFlutterModule(ModuleUtilCore.findModuleForPsiElement(element)); } /** * Return the Flutter {@link Workspace} if there is at least one module that is determined to be a Flutter module by the workspace, and * has the Dart SDK enabled module. */ @Nullable public static Workspace getFlutterBazelWorkspace(@Nullable Project project) { if (project == null || project.isDisposed()) return null; final Workspace workspace = WorkspaceCache.getInstance(project).get(); if (workspace == null) return null; for (Module module : getModules(project)) { if (DartPlugin.isDartSdkEnabled(module)) { return workspace; } } return null; } /** * Return true if the passed {@link Project} is a Bazel Flutter {@link Project}. If the {@link Workspace} is needed after this call, * {@link #getFlutterBazelWorkspace(Project)} should be used. */ public static boolean isFlutterBazelProject(@Nullable Project project) { return getFlutterBazelWorkspace(project) != null; } @Nullable public static VirtualFile findXcodeProjectFile(@NotNull Project project, @Nullable VirtualFile selectedFile) { if (selectedFile == null) { // This should not happen because the action should not be visible if there is no selection, but ... return findXcodeProjectFile(project); } VirtualFile dir = selectedFile; while (dir != null) { String name = dir.getName(); if ("ios".equals(name) || ".ios".equals(name) || "macos".equals(name)) { // If needed, we could add a check that the parent of dir contains pubspec.yaml, but this is probably adequate. VirtualFile file = findPreferedXcodeMetadataFile(dir); if (file != null) { return file; } } dir = dir.getParent(); } return null; } @Nullable private static VirtualFile findXcodeProjectFile(@NotNull Project project) { if (project.isDisposed()) return null; // Look for Xcode metadata file in `ios/`. for (PubRoot root : PubRoots.forProject(project)) { final VirtualFile dir = root.getiOsDir(); final VirtualFile file = findPreferedXcodeMetadataFile(dir); if (file != null) { return file; } } // Look for Xcode metadata in `example/ios/`. for (PubRoot root : PubRoots.forProject(project)) { final VirtualFile exampleDir = root.getExampleDir(); if (exampleDir != null) { VirtualFile iosDir = exampleDir.findChild("ios"); if (iosDir == null) { iosDir = exampleDir.findChild(".ios"); } final VirtualFile file = findPreferedXcodeMetadataFile(iosDir); if (file != null) { return file; } } } return null; } @Nullable private static VirtualFile findPreferedXcodeMetadataFile(@Nullable VirtualFile iosDir) { if (iosDir != null) { // Prefer .xcworkspace. for (VirtualFile child : iosDir.getChildren()) { if (FlutterUtils.isXcodeWorkspaceFileName(child.getName())) { return child; } } // But fall-back to a project. for (VirtualFile child : iosDir.getChildren()) { if (FlutterUtils.isXcodeProjectFileName(child.getName())) { return child; } } } return null; } @NotNull public static Module[] getModules(@NotNull Project project) { // A disposed project has no modules. if (project.isDisposed()) return Module.EMPTY_ARRAY; return ModuleManager.getInstance(project).getModules(); } /** * Check if any module in this project {@link #declaresFlutter(Module)}. */ public static boolean declaresFlutter(@NotNull Project project) { if (project.isDisposed()) return false; return CollectionUtils.anyMatch(getModules(project), FlutterModuleUtils::declaresFlutter); } /** * Ensures a Flutter run configuration is selected in the run pull down. */ public static void ensureRunConfigSelected(@NotNull Project project) { if (project.isDisposed()) return; final FlutterRunConfigurationType configType = FlutterRunConfigurationType.getInstance(); final RunManager runManager = RunManager.getInstance(project); if (!runManager.getConfigurationsList(configType).isEmpty()) { if (runManager.getSelectedConfiguration() == null) { final List<RunnerAndConfigurationSettings> flutterConfigs = runManager.getConfigurationSettingsList(configType); if (!flutterConfigs.isEmpty()) { runManager.setSelectedConfiguration(flutterConfigs.get(0)); } } } } /** * Creates a Flutter run configuration if none exists. */ public static void autoCreateRunConfig(@NotNull Project project, @NotNull PubRoot root) { assert ApplicationManager.getApplication().isReadAccessAllowed(); if (project.isDisposed()) return; VirtualFile main = root.getLibMain(); if (main == null || !main.exists()) { // Check for example main.dart in plugins main = root.getExampleLibMain(); if (main == null || !main.exists()) { return; } } final FlutterRunConfigurationType configType = FlutterRunConfigurationType.getInstance(); final RunManager runManager = RunManager.getInstance(project); if (!runManager.getConfigurationsList(configType).isEmpty()) { // Don't create a run config if one already exists. return; } final RunnerAndConfigurationSettings settings = runManager.createConfiguration(project.getName(), configType.getFactory()); final SdkRunConfig config = (SdkRunConfig)settings.getConfiguration(); // Set config name. config.setName("main.dart"); // Set fields. final SdkFields fields = new SdkFields(); fields.setFilePath(main.getPath()); config.setFields(fields); runManager.addConfiguration(settings); runManager.setSelectedConfiguration(settings); } /** * If no files are open, or just the readme, show lib/main.dart for the given PubRoot. */ public static void autoShowMain(@NotNull Project project, @NotNull PubRoot root) { if (project.isDisposed()) return; final VirtualFile main = root.getFileToOpen(); if (main == null) return; DumbService.getInstance(project).runWhenSmart(() -> { final FileEditorManager manager = FileEditorManager.getInstance(project); FileEditor[] editors = manager.getAllEditors(); if (editors.length > 1) { return; } for (FileEditor editor : editors) { VirtualFile file = editor.getFile(); if (file.equals(main)) { return; } if (file.getFileType().equals(DartFileType.INSTANCE)) { return; } } manager.openFile(main, editors.length == 0); }); } /** * Introspect into the module's content roots, looking for a pubspec.yaml that references flutter. * <p/> * True is returned if any of the PubRoots associated with the {@link Module} have a pubspec that declares flutter. */ public static boolean declaresFlutter(@NotNull Module module) { try { final PubRootCache cache = PubRootCache.getInstance(module.getProject()); for (PubRoot root : cache.getRoots(module)) { if (root.declaresFlutter()) { return true; } } return false; } catch (AlreadyDisposedException ignored) { return false; } } /** * Find flutter modules. * <p> * Flutter modules are defined as: * 1. being tagged with the #FlutterModuleType, or * 2. containing a pubspec that #declaresFlutterDependency */ @NotNull public static List<Module> findModulesWithFlutterContents(@NotNull Project project) { return CollectionUtils.filter(getModules(project), module -> isFlutterModule(module) || declaresFlutter(module)); } public static boolean convertFromDeprecatedModuleType(@NotNull Project project) { boolean modulesConverted = false; // Only automatically convert from older module types to JAVA_MODULE types if we're running in Android Studio. if (FlutterUtils.isAndroidStudio()) { for (Module module : getModules(project)) { if (isDeprecatedFlutterModuleType(module)) { setFlutterModuleType(module); modulesConverted = true; } } } return modulesConverted; } // Return true if there is a module with the same name as the project plus the Android suffix. public static boolean hasAndroidModule(@NotNull Project project) { for (PubRoot root : PubRoots.forProject(project)) { assert root != null; String name = PubspecYamlUtil.getDartProjectName(root.getPubspec()); String moduleName = name + "_android"; for (Module module : FlutterModuleUtils.getModules(project)) { if (moduleName.equals(module.getName())) { return true; } } } return false; } public static boolean isDeprecatedFlutterModuleType(@NotNull Module module) { if (!DEPRECATED_FLUTTER_MODULE_TYPE_ID.equals(module.getOptionValue("type"))) { return false; } // Validate that the pubspec references flutter. return declaresFlutter(module); } public static boolean isInFlutterAndroidModule(@NotNull Project project, @NotNull VirtualFile file) { final Module module = FlutterBuildActionGroup.findFlutterModule(project, file); if (module != null) { for (Facet<?> facet : FacetManager.getInstance(module).getAllFacets()) { if ("Android".equals(facet.getName())) { return declaresFlutter(project); } } } return false; } /** * Set the passed module to the module type used by Flutter, defined by {@link #getModuleTypeIDForFlutter()}. */ public static void setFlutterModuleType(@NotNull Module module) { module.setModuleType(getModuleTypeIDForFlutter()); } public static void setFlutterModuleAndReload(@NotNull Module module, @NotNull Project project) { if (project.isDisposed()) return; setFlutterModuleType(module); enableDartSDK(module); project.save(); EditorNotifications.getInstance(project).updateAllNotifications(); ProjectManager.getInstance().reloadProject(project); } public static void enableDartSDK(@NotNull Module module) { if (FlutterSdk.getFlutterSdk(module.getProject()) != null) { return; } // parse the .dart_tool/flutter_config.json or .packages file String sdkPath = FlutterSdkUtil.guessFlutterSdkFromPackagesFile(module); if (sdkPath != null) { FlutterSdkUtil.updateKnownSdkPaths(sdkPath); } // try and locate flutter on the path if (sdkPath == null) { sdkPath = FlutterSdkUtil.locateSdkFromPath(); if (sdkPath != null) { FlutterSdkUtil.updateKnownSdkPaths(sdkPath); } } if (sdkPath == null) { final String[] flutterSdkPaths = FlutterSdkUtil.getKnownFlutterSdkPaths(); if (flutterSdkPaths.length > 0) { sdkPath = flutterSdkPaths[0]; } } if (sdkPath != null) { final FlutterSdk flutterSdk = FlutterSdk.forPath(sdkPath); if (flutterSdk == null) { return; } final String dartSdkPath = flutterSdk.getDartSdkPath(); if (dartSdkPath == null) { return; // Not cached. TODO call flutterSdk.sync() here? } ApplicationManager.getApplication().runWriteAction(() -> { DartPlugin.ensureDartSdkConfigured(module.getProject(), dartSdkPath); DartPlugin.enableDartSdk(module); }); } } }
flutter-intellij/flutter-idea/src/io/flutter/utils/FlutterModuleUtils.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/FlutterModuleUtils.java", "repo_id": "flutter-intellij", "token_count": 5764 }
454
/* * 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.dartlang.vm.service.VmServiceListener; import org.dartlang.vm.service.element.Event; public abstract class VmServiceListenerAdapter implements VmServiceListener { @Override public void connectionOpened() { } @Override public void received(String streamId, Event event) { } @Override public void connectionClosed() { } }
flutter-intellij/flutter-idea/src/io/flutter/utils/VmServiceListenerAdapter.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/utils/VmServiceListenerAdapter.java", "repo_id": "flutter-intellij", "token_count": 159 }
455
/* * Copyright 2022 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package io.flutter.view; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.wm.ToolWindow; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentManager; import icons.FlutterIcons; import io.flutter.FlutterInitializer; import io.flutter.analytics.Analytics; import io.flutter.devtools.DevToolsUrl; import io.flutter.utils.AsyncUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.function.Function; class BrowserTab { protected EmbeddedTab embeddedTab; protected Content content; protected CompletableFuture<DevToolsUrl> devToolsUrlFuture; } public abstract class EmbeddedBrowser { public static final String ANALYTICS_CATEGORY = "embedded-browser"; protected final Map<@NotNull String, @NotNull BrowserTab> tabs = new HashMap<>(); public abstract Logger logger(); private final Analytics analytics; public EmbeddedBrowser(Project project) { this.analytics = FlutterInitializer.getAnalytics(); ProjectManager.getInstance().addProjectManagerListener(project, new ProjectManagerListener() { @Override public void projectClosing(@NotNull Project project) { for (final String tabName: tabs.keySet()) { final BrowserTab tab = tabs.get(tabName); if (tab.embeddedTab != null) { try { tab.embeddedTab.close(); } catch (Exception ex) { logger().info(ex); } } } tabs.clear(); } }); } public void openPanel(ContentManager contentManager, String tabName, DevToolsUrl devToolsUrl, Consumer<String> onBrowserUnavailable) { final BrowserTab firstTab = tabs.get(tabName); if (firstTab == null) { try { openBrowserTabFor(tabName); } catch (Exception ex) { analytics.sendEvent(ANALYTICS_CATEGORY, "openBrowserTabFailed-" + this.getClass()); onBrowserUnavailable.accept(ex.getMessage()); return; } } final BrowserTab tab = tabs.get(tabName); // If the browser failed to start during setup, run unavailable callback. if (tab == null) { onBrowserUnavailable.accept("Browser failed to start during setup."); return; } // Multiple LoadFinished events can occur, but we only need to add content the first time. final AtomicBoolean contentLoaded = new AtomicBoolean(false); try { tab.embeddedTab.loadUrl(devToolsUrl.getUrlString()); } catch (Exception ex) { tab.devToolsUrlFuture.completeExceptionally(ex); onBrowserUnavailable.accept(ex.getMessage()); logger().info(ex); return; } tab.devToolsUrlFuture.complete(devToolsUrl); JComponent component = tab.embeddedTab.getTabComponent(contentManager); ApplicationManager.getApplication().invokeLater(() -> { if (contentManager.isDisposed()) { return; } contentManager.removeAllContents(false); for (final String otherTabName: tabs.keySet()) { if (otherTabName.equals(tabName)) { continue; } final BrowserTab browserTab = tabs.get(otherTabName); contentManager.addContent(browserTab.content); } tab.content = contentManager.getFactory().createContent(null, tabName, false); tab.content.setComponent(component); tab.content.putUserData(ToolWindow.SHOW_CONTENT_ICON, Boolean.TRUE); // TODO(helin24): Use differentiated icons for each tab and copy from devtools toolbar. tab.content.setIcon(FlutterIcons.Phone); contentManager.addContent(tab.content); contentManager.setSelectedContent(tab.content, true); }); } private BrowserTab openBrowserTabFor(String tabName) throws Exception { BrowserTab tab = new BrowserTab(); tab.devToolsUrlFuture = new CompletableFuture<>(); tab.embeddedTab = openEmbeddedTab(); tabs.put(tabName, tab); return tab; } public abstract EmbeddedTab openEmbeddedTab() throws Exception; public void updatePanelToWidget(String widgetId) { updateUrlAndReload(devToolsUrl -> { devToolsUrl.widgetId = widgetId; return devToolsUrl; }); } public void updateColor(String newColor) { updateUrlAndReload(devToolsUrl -> { if (devToolsUrl.colorHexCode.equals(newColor)) { return null; } devToolsUrl.colorHexCode = newColor; return devToolsUrl; }); } public void updateFontSize(float newFontSize) { updateUrlAndReload(devToolsUrl -> { if (devToolsUrl.fontSize.equals(newFontSize)) { return null; } devToolsUrl.fontSize = newFontSize; return devToolsUrl; }); } private void updateUrlAndReload(Function<DevToolsUrl, DevToolsUrl> newDevToolsUrlFn) { this.tabs.forEach((tabName, tab) -> { final CompletableFuture<DevToolsUrl> updatedUrlFuture = tab.devToolsUrlFuture.thenApply(devToolsUrl -> { if (devToolsUrl == null) { // This happens if URL has already been reset (e.g. new app has started). In this case [openPanel] should be called again instead of // modifying the URL. return null; } return newDevToolsUrlFn.apply(devToolsUrl); }); AsyncUtils.whenCompleteUiThread(updatedUrlFuture, (devToolsUrl, ex) -> { if (ex != null) { logger().info(ex); FlutterInitializer.getAnalytics().sendExpectedException("browser-update", ex); return; } if (devToolsUrl == null) { // Reload is no longer needed - either URL has been reset or there has been no change. return; } tab.embeddedTab.loadUrl(devToolsUrl.getUrlString()); }); }); } }
flutter-intellij/flutter-idea/src/io/flutter/view/EmbeddedBrowser.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/EmbeddedBrowser.java", "repo_id": "flutter-intellij", "token_count": 2301 }
456
/* * 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. */ /* * Copyright 2000-2017 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.view; import com.intellij.ide.BrowserUtil; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.*; import com.intellij.ui.paint.EffectPainter; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import gnu.trove.TIntIntHashMap; import org.intellij.lang.annotations.JdkConstants; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleRole; import javax.swing.*; import javax.swing.border.Border; import javax.swing.tree.TreeCellRenderer; import java.awt.*; import java.awt.font.FontRenderContext; import java.awt.font.TextAttribute; import java.awt.font.TextLayout; import java.text.AttributedCharacterIterator; import java.text.AttributedString; import java.text.CharacterIterator; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * This is high performance Swing component which represents * colored text with multiple icons. The text consists of fragments. Each * text fragment has its own color (foreground) and font style. * * @author Vladimir Kondratyev */ @SuppressWarnings({"NonPrivateFieldAccessedInSynchronizedContext", "FieldAccessedSynchronizedAndUnsynchronized"}) public class MultiIconSimpleColoredComponent extends JComponent implements Accessible, ColoredTextContainer { static class PositionedIcon { final Icon icon; final int index; public PositionedIcon(Icon icon, int index) { this.icon = icon; this.index = index; } } private static final Logger LOG = Logger.getInstance(MultiIconSimpleColoredComponent.class); public static final Color SHADOW_COLOR = new JBColor(new Color(250, 250, 250, 140), Gray._0.withAlpha(50)); public static final Color STYLE_SEARCH_MATCH_BACKGROUND = SHADOW_COLOR; //api compatibility public static final int FRAGMENT_ICON = -100; private final List<String> myFragments; private final List<TextLayout> myLayouts; private final List<PositionedIcon> myIcons; private Font myLayoutFont; private final List<SimpleTextAttributes> myAttributes; private List<Object> myFragmentTags = null; private TIntIntHashMap myFragmentAlignment; /** * Internal padding */ private Insets myIpad; /** * Gap between icon and text. It is used only if icon is defined. */ protected int myIconTextGap; /** * Defines whether the focus border around the text is painted or not. * For example, text can have a border if the component represents a selected item * in focused JList. */ private boolean myPaintFocusBorder; /** * Defines whether the focus border around the text extends to icon or not */ private boolean myFocusBorderAroundIcon; /** * This is the border around the text. For example, text can have a border * if the component represents a selected item in a focused JList. * Border can be <code>null</code>. */ private Border myBorder; private int myMainTextLastIndex = -1; private final TIntIntHashMap myFragmentPadding; @JdkConstants.HorizontalAlignment private int myTextAlign = SwingConstants.LEFT; private boolean myIconOpaque = false; private boolean myAutoInvalidate = !(this instanceof TreeCellRenderer); private boolean myTransparentIconBackground; public MultiIconSimpleColoredComponent() { myFragments = new ArrayList<>(3); myLayouts = new ArrayList<>(3); myAttributes = new ArrayList<>(3); myIcons = new ArrayList<>(3); myIpad = new JBInsets(1, 2, 1, 2); myIconTextGap = JBUI.scale(2); myBorder = new MyBorder(); myFragmentPadding = new TIntIntHashMap(10); myFragmentAlignment = new TIntIntHashMap(10); setOpaque(true); updateUI(); } @Override public void updateUI() { UISettings.setupComponentAntialiasing(this); } @NotNull public ColoredIterator iterator() { return new MyIterator(); } @NotNull public final MultiIconSimpleColoredComponent append(@NotNull String fragment) { append(fragment, SimpleTextAttributes.REGULAR_ATTRIBUTES); return this; } /** * Appends string fragments to existing ones. Appended string * will have specified <code>attributes</code>. * * @param fragment text fragment * @param attributes text attributes */ @Override public final void append(@NotNull final String fragment, @NotNull final SimpleTextAttributes attributes) { append(fragment, attributes, myMainTextLastIndex < 0); } /** * Appends text fragment and sets it's end offset and alignment. * See SimpleColoredComponent#appendTextPadding for details * * @param fragment text fragment * @param attributes text attributes * @param padding end offset of the text * @param align alignment between current offset and padding */ public final void append(@NotNull final String fragment, @NotNull final SimpleTextAttributes attributes, int padding, @JdkConstants.HorizontalAlignment int align) { append(fragment, attributes, myMainTextLastIndex < 0); appendTextPadding(padding, align); } /** * Appends string fragments to existing ones. Appended string * will have specified <code>attributes</code>. * * @param fragment text fragment * @param attributes text attributes * @param isMainText main text of not */ public void append(@NotNull final String fragment, @NotNull final SimpleTextAttributes attributes, boolean isMainText) { _append(fragment, attributes, isMainText); revalidateAndRepaint(); } private synchronized void _append(@NotNull final String fragment, @NotNull final SimpleTextAttributes attributes, boolean isMainText) { myFragments.add(fragment); myAttributes.add(attributes); if (isMainText) { myMainTextLastIndex = myFragments.size() - 1; } } void revalidateAndRepaint() { if (myAutoInvalidate) { revalidate(); } repaint(); } @Override public void append(@NotNull final String fragment, @NotNull final SimpleTextAttributes attributes, Object tag) { _append(fragment, attributes, tag); revalidateAndRepaint(); } /** * Adds the icon at the beginning of the line unlike addIcon, which adds the * icon after the already appended text. */ @Override public void setIcon(@Nullable Icon icon) { assert (myIcons.isEmpty()); if (icon == null) { return; } myIcons.add(new PositionedIcon(icon, 0)); } private synchronized void _append(String fragment, SimpleTextAttributes attributes, Object tag) { append(fragment, attributes); if (myFragmentTags == null) { myFragmentTags = new ArrayList<>(); } while (myFragmentTags.size() < myFragments.size() - 1) { myFragmentTags.add(null); } myFragmentTags.add(tag); } /** * fragment width isn't a right name, it is actually a padding * * @deprecated remove in IDEA 16 */ @Deprecated public synchronized void appendFixedTextFragmentWidth(int width) { appendTextPadding(width); } public synchronized void appendTextPadding(int padding) { appendTextPadding(padding, SwingConstants.LEFT); } /** * @param padding end offset that will be set after drawing current text fragment * @param align alignment of the current text fragment, if it is SwingConstants.RIGHT * or SwingConstants.TRAILING then the text fragment will be aligned to the right at * the padding, otherwise it will be aligned to the left */ public synchronized void appendTextPadding(int padding, @JdkConstants.HorizontalAlignment int align) { final int alignIndex = myFragments.size() - 1; myFragmentPadding.put(alignIndex, padding); myFragmentAlignment.put(alignIndex, align); } public void setTextAlign(@JdkConstants.HorizontalAlignment int align) { myTextAlign = align; } /** * Clear all special attributes of <code>SimpleColoredComponent</code>. * They are icon, text fragments and their attributes, "paint focus border". */ public void clear() { _clear(); revalidateAndRepaint(); } private synchronized void _clear() { myPaintFocusBorder = false; myIcons.clear(); myFragments.clear(); myLayouts.clear(); myAttributes.clear(); myFragmentTags = null; myMainTextLastIndex = -1; myFragmentPadding.clear(); } /** * Sets a new component icon * * @param icon icon */ public final void addIcon(@NotNull final Icon icon) { assert (icon != null); assert (myFragments.size() == myAttributes.size()); // Add an icon that should be displayed after any already inserted fragments. myIcons.add(new PositionedIcon(icon, myFragments.size())); revalidateAndRepaint(); } /** * @return "leave" (internal) internal paddings of the component */ @NotNull public Insets getIpad() { return myIpad; } /** * Sets specified internal paddings * * @param ipad insets */ public void setIpad(@NotNull Insets ipad) { myIpad = ipad; revalidateAndRepaint(); } /** * @return gap between icon and text */ public int getIconTextGap() { return myIconTextGap; } /** * Sets a new gap between icon and text * * @param iconTextGap the gap between text and icon * @throws IllegalArgumentException if the <code>iconTextGap</code> * has a negative value */ public void setIconTextGap(final int iconTextGap) { if (iconTextGap < 0) { throw new IllegalArgumentException("wrong iconTextGap: " + iconTextGap); } myIconTextGap = iconTextGap; revalidateAndRepaint(); } public Border getMyBorder() { return myBorder; } public void setMyBorder(@Nullable Border border) { myBorder = border; } /** * Sets whether focus border is painted or not * * @param paintFocusBorder <code>true</code> or <code>false</code> */ protected final void setPaintFocusBorder(final boolean paintFocusBorder) { myPaintFocusBorder = paintFocusBorder; repaint(); } /** * Sets whether focus border extends to icon or not. If so then * component also extends the selection. * * @param focusBorderAroundIcon <code>true</code> or <code>false</code> */ protected final void setFocusBorderAroundIcon(final boolean focusBorderAroundIcon) { myFocusBorderAroundIcon = focusBorderAroundIcon; repaint(); } public boolean isIconOpaque() { return myIconOpaque; } public void setIconOpaque(final boolean iconOpaque) { myIconOpaque = iconOpaque; repaint(); } @Override @NotNull public Dimension getPreferredSize() { return computePreferredSize(false); } @Override @NotNull public Dimension getMinimumSize() { return computePreferredSize(false); } @Nullable public synchronized Object getFragmentTag(int index) { if (myFragmentTags != null && index < myFragmentTags.size()) { return myFragmentTags.get(index); } return null; } @NotNull public final synchronized Dimension computePreferredSize(final boolean mainTextOnly) { // Calculate width int width = myIpad.left; for (PositionedIcon icon : myIcons) { width += icon.icon.getIconWidth() + myIconTextGap; } final Insets borderInsets = myBorder != null ? myBorder.getBorderInsets(this) : JBUI.emptyInsets(); width += borderInsets.left; final Font font = getBaseFont(); width += computeTextWidth(font, mainTextOnly); width += myIpad.right + borderInsets.right; // Take into account that the component itself can have a border final Insets insets = getInsets(); if (insets != null) { width += insets.left + insets.right; } final int height = computePreferredHeight(); return new Dimension(width, height); } public final synchronized int computePreferredHeight() { int height = myIpad.top + myIpad.bottom; final Font font = getBaseFont(); final FontMetrics metrics = getFontMetrics(font); int textHeight = Math.max(JBUI.scale(16), metrics.getHeight()); //avoid too narrow rows final Insets borderInsets = myBorder != null ? myBorder.getBorderInsets(this) : JBUI.emptyInsets(); textHeight += borderInsets.top + borderInsets.bottom; if (!myIcons.isEmpty()) { for (PositionedIcon icon : myIcons) { height += Math.max(icon.icon.getIconHeight(), textHeight); } } else { height += textHeight; } // Take into account that the component itself can have a border final Insets insets = getInsets(); if (insets != null) { height += insets.top + insets.bottom; } return height; } private Rectangle computePaintArea() { final Rectangle area = new Rectangle(getWidth(), getHeight()); JBInsets.removeFrom(area, getInsets()); JBInsets.removeFrom(area, myIpad); return area; } private float computeTextWidth(@NotNull Font font, final boolean mainTextOnly) { float result = 0; final int baseSize = font.getSize(); boolean wasSmaller = false; for (int i = 0; i < myAttributes.size(); i++) { final SimpleTextAttributes attributes = myAttributes.get(i); final boolean isSmaller = attributes.isSmaller(); if (font.getStyle() != attributes.getFontStyle() || isSmaller != wasSmaller) { // derive font only if it is necessary font = font.deriveFont(attributes.getFontStyle(), isSmaller ? UIUtil.getFontSize(UIUtil.FontSize.SMALL) : baseSize); } wasSmaller = isSmaller; result += computeStringWidth(i, font); final int fixedWidth = myFragmentPadding.get(i); if (fixedWidth > 0 && result < fixedWidth) { result = fixedWidth; } if (mainTextOnly && myMainTextLastIndex >= 0 && i == myMainTextLastIndex) break; } return result; } @NotNull private Font getBaseFont() { Font font = getFont(); if (font == null) font = UIUtil.getLabelFont(); return font; } private TextLayout getTextLayout(int fragmentIndex, Font font, FontRenderContext frc) { if (getBaseFont() != myLayoutFont) myLayouts.clear(); TextLayout layout = fragmentIndex < myLayouts.size() ? myLayouts.get(fragmentIndex) : null; if (layout == null && needFontFallback(font, myFragments.get(fragmentIndex))) { layout = createAndCacheTextLayout(fragmentIndex, font, frc); } return layout; } private void doDrawString(Graphics2D g, int fragmentIndex, float x, float y) { final String text = myFragments.get(fragmentIndex); if (StringUtil.isEmpty(text)) return; final TextLayout layout = getTextLayout(fragmentIndex, g.getFont(), g.getFontRenderContext()); if (layout != null) { layout.draw(g, x, y); } else { g.drawString(text, x, y); } } private float computeStringWidth(int fragmentIndex, Font font) { final String text = myFragments.get(fragmentIndex); if (StringUtil.isEmpty(text)) return 0; final FontRenderContext fontRenderContext = getFontMetrics(font).getFontRenderContext(); final TextLayout layout = getTextLayout(fragmentIndex, font, fontRenderContext); if (layout != null) { return layout.getAdvance(); } else { return (float)font.getStringBounds(text, fontRenderContext).getWidth(); } } private TextLayout createAndCacheTextLayout(int fragmentIndex, Font basefont, FontRenderContext fontRenderContext) { final String text = myFragments.get(fragmentIndex); final AttributedString string = new AttributedString(text); final int start = 0; final int end = text.length(); final AttributedCharacterIterator it = string.getIterator(new AttributedCharacterIterator.Attribute[0], start, end); Font currentFont = basefont; int currentIndex = start; for (char c = it.first(); c != CharacterIterator.DONE; c = it.next()) { final Font font = basefont; // TODO(jacobr): SuitableFontProvider is a private class so we can't // easily use it. How important is supporting this use case? /* if (!font.canDisplay(c)) { for (SuitableFontProvider provider : SuitableFontProvider.EP_NAME.getExtensions()) { font = provider.getFontAbleToDisplay(c, basefont.getSize(), basefont.getStyle(), basefont.getFamily()); if (font != null) break; } } */ final int i = it.getIndex(); if (!Comparing.equal(currentFont, font)) { if (i > currentIndex) { string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, i); } currentFont = font; currentIndex = i; } } if (currentIndex < end) { string.addAttribute(TextAttribute.FONT, currentFont, currentIndex, end); } final TextLayout layout = new TextLayout(string.getIterator(), fontRenderContext); if (fragmentIndex >= myLayouts.size()) { myLayouts.addAll(Collections.nCopies(fragmentIndex - myLayouts.size() + 1, null)); } myLayouts.set(fragmentIndex, layout); myLayoutFont = getBaseFont(); return layout; } private static boolean needFontFallback(Font font, String text) { return font.canDisplayUpTo(text) != -1 && text.indexOf(CharacterIterator.DONE) == -1; // see IDEA-137517, TextLayout does not support this character } /** * Returns the index of text fragment at the specified X offset. * * @param x the offset * @return the index of the fragment, {@link #FRAGMENT_ICON} if the icon is at the offset, or -1 if nothing is there. */ public int findFragmentAt(int x) { float curX = myIpad.left; if (myBorder != null) { curX += myBorder.getBorderInsets(this).left; } curX += computeTextAlignShift(); Font font = getBaseFont(); final int baseSize = font.getSize(); boolean wasSmaller = false; int i = 0; int iconIndex = 0; while (true) { // Go through all icons before attribute i. while (iconIndex < myIcons.size() && myIcons.get(iconIndex).index <= i) { final int iconWidth = myIcons.get(iconIndex).icon.getIconWidth() + myIconTextGap * 2; if (x >= curX && x < curX + iconWidth) { return FRAGMENT_ICON - iconIndex; } curX += iconWidth; iconIndex++; } if (i >= myAttributes.size()) { break; } final SimpleTextAttributes attributes = myAttributes.get(i); final boolean isSmaller = attributes.isSmaller(); if (font.getStyle() != attributes.getFontStyle() || isSmaller != wasSmaller) { // derive font only if it is necessary font = font.deriveFont(attributes.getFontStyle(), isSmaller ? UIUtil.getFontSize(UIUtil.FontSize.SMALL) : baseSize); } wasSmaller = isSmaller; final float curWidth = computeStringWidth(i, font); if (x >= curX && x < curX + curWidth) { return i; } curX += curWidth; final int fragmentPadding = myFragmentPadding.get(i); if (fragmentPadding > 0 && curX < fragmentPadding) { curX = fragmentPadding; } i++; } return -1; } @Nullable public Object getFragmentTagAt(int x) { final int index = findFragmentAt(x); return index < 0 ? null : getFragmentTag(index); } @Nullable public Icon getIconAt(int x) { final int index = findFragmentAt(x); return index <= FRAGMENT_ICON ? myIcons.get(FRAGMENT_ICON - index).icon : null; } @NotNull protected JLabel formatToLabel(@NotNull JLabel label) { // TODO(jacobr): interleave icons inline? label.setIcon(!myIcons.isEmpty() ? myIcons.get(0).icon : null); if (!myFragments.isEmpty()) { final StringBuilder text = new StringBuilder(); text.append("<html><body style=\"white-space:nowrap\">"); for (int i = 0; i < myFragments.size(); i++) { final String fragment = myFragments.get(i); final SimpleTextAttributes attributes = myAttributes.get(i); final Object tag = getFragmentTag(i); if (tag instanceof BrowserLauncherTag) { formatLink(text, fragment, attributes, ((BrowserLauncherTag)tag).myUrl); } else { formatText(text, fragment, attributes); } } text.append("</body></html>"); label.setText(text.toString()); } return label; } static void formatText(@NotNull StringBuilder builder, @NotNull String fragment, @NotNull SimpleTextAttributes attributes) { if (!fragment.isEmpty()) { builder.append("<span"); formatStyle(builder, attributes); builder.append('>').append(convertFragment(fragment)).append("</span>"); } } static void formatLink(@NotNull StringBuilder builder, @NotNull String fragment, @NotNull SimpleTextAttributes attributes, @NotNull String url) { if (!fragment.isEmpty()) { builder.append("<a href=\"").append(StringUtil.replace(url, "\"", "%22")).append("\""); formatStyle(builder, attributes); builder.append('>').append(convertFragment(fragment)).append("</a>"); } } private static String convertFragment(@NotNull String fragment) { return StringUtil.escapeXmlEntities(fragment).replaceAll("\\\\n", "<br>"); } private static void formatStyle(final StringBuilder builder, final SimpleTextAttributes attributes) { final Color fgColor = attributes.getFgColor(); final Color bgColor = attributes.getBgColor(); final int style = attributes.getStyle(); final int pos = builder.length(); if (fgColor != null) { builder.append("color:#").append(Integer.toString(fgColor.getRGB() & 0xFFFFFF, 16)).append(';'); } if (bgColor != null) { builder.append("background-color:#").append(Integer.toString(bgColor.getRGB() & 0xFFFFFF, 16)).append(';'); } if ((style & SimpleTextAttributes.STYLE_BOLD) != 0) { builder.append("font-weight:bold;"); } if ((style & SimpleTextAttributes.STYLE_ITALIC) != 0) { builder.append("font-style:italic;"); } if ((style & SimpleTextAttributes.STYLE_UNDERLINE) != 0) { builder.append("text-decoration:underline;"); } else if ((style & SimpleTextAttributes.STYLE_STRIKEOUT) != 0) { builder.append("text-decoration:line-through;"); } if (builder.length() > pos) { builder.insert(pos, " style=\""); builder.append('"'); } } @Override protected void paintComponent(final Graphics g) { try { _doPaint(g); } catch (RuntimeException e) { LOG.warn(logSwingPath(), e); throw e; } } private synchronized void _doPaint(final Graphics g) { checkCanPaint(g); doPaint((Graphics2D)g); } protected void doPaint(final Graphics2D g) { doPaintTextBackground(g, 0); doPaintTextAndIcons(g, myFocusBorderAroundIcon || myIcons.isEmpty()); } private void doPaintTextBackground(Graphics2D g, int offset) { if (isOpaque() || shouldDrawBackground()) { paintBackground(g, offset, getWidth() - offset, getHeight()); } } protected void paintBackground(Graphics2D g, int x, int width, int height) { g.setColor(getBackground()); g.fillRect(x, 0, width, height); } protected void doPaintIcon(@NotNull Graphics2D g, @NotNull Icon icon, int offset) { final Container parent = getParent(); Color iconBackgroundColor = null; if ((isOpaque() || isIconOpaque()) && !isTransparentIconBackground()) { if (parent != null && !myFocusBorderAroundIcon && !UIUtil.isFullRowSelectionLAF()) { iconBackgroundColor = parent.getBackground(); } else { iconBackgroundColor = getBackground(); } } if (iconBackgroundColor != null) { g.setColor(iconBackgroundColor); g.fillRect(offset, 0, icon.getIconWidth() + myIpad.left + myIconTextGap, getHeight()); } paintIcon(g, icon, offset + myIpad.left); } protected int doPaintTextAndIcons(Graphics2D g, boolean focusAroundIcon) { float offset = myIpad.left; if (myBorder != null) { offset += myBorder.getBorderInsets(this).left; } final List<Object[]> searchMatches = new ArrayList<>(); applyAdditionalHints(g); final Font baseFont = getBaseFont(); g.setFont(baseFont); offset += computeTextAlignShift(); final int baseSize = baseFont.getSize(); final FontMetrics baseMetrics = g.getFontMetrics(); final Rectangle area = computePaintArea(); final int textBaseline = area.y + getTextBaseLine(baseMetrics, area.height); boolean wasSmaller = false; assert (myFragments.size() == myAttributes.size()); int i = 0; int iconIndex = 0; while (true) { // Go through all icons up to attribute i. while (iconIndex < myIcons.size() && myIcons.get(iconIndex).index <= i) { final Icon icon = myIcons.get(iconIndex).icon; final int iconWidth = icon.getIconWidth() + myIconTextGap; doPaintIcon(g, icon, (int)offset); offset += iconWidth + myIconTextGap; iconIndex++; } if (i >= myFragments.size()) { break; } final SimpleTextAttributes attributes = myAttributes.get(i); Font font = g.getFont(); final boolean isSmaller = attributes.isSmaller(); if (font.getStyle() != attributes.getFontStyle() || isSmaller != wasSmaller) { // derive font only if it is necessary font = font.deriveFont(attributes.getFontStyle(), isSmaller ? UIUtil.getFontSize(UIUtil.FontSize.SMALL) : baseSize); } wasSmaller = isSmaller; g.setFont(font); final FontMetrics metrics = g.getFontMetrics(font); final float fragmentWidth = computeStringWidth(i, font); final int fragmentPadding = myFragmentPadding.get(i); final Color bgColor = attributes.isSearchMatch() ? null : attributes.getBgColor(); if ((attributes.isOpaque() || isOpaque()) && bgColor != null) { g.setColor(bgColor); g.fillRect((int)offset, 0, (int)fragmentWidth, getHeight()); } Color color = attributes.getFgColor(); if (color == null) { // in case if color is not defined we have to get foreground color from Swing hierarchy color = getForeground(); } if (!isEnabled()) { color = UIUtil.getInactiveTextColor(); } g.setColor(color); final int fragmentAlignment = myFragmentAlignment.get(i); final float endOffset; if (fragmentPadding > 0 && fragmentPadding > fragmentWidth) { endOffset = fragmentPadding; if (fragmentAlignment == SwingConstants.RIGHT || fragmentAlignment == SwingConstants.TRAILING) { offset = fragmentPadding - fragmentWidth; } } else { endOffset = offset + fragmentWidth; } if (!attributes.isSearchMatch()) { if (shouldDrawMacShadow()) { g.setColor(SHADOW_COLOR); doDrawString(g, i, offset, textBaseline + 1); } if (shouldDrawDimmed()) { color = ColorUtil.dimmer(color); } g.setColor(color); doDrawString(g, i, offset, textBaseline); } // for some reason strokeState here may be incorrect, resetting the stroke helps g.setStroke(g.getStroke()); // 1. Strikeout effect if (attributes.isStrikeout() && !attributes.isSearchMatch()) { EffectPainter.STRIKE_THROUGH.paint(g, (int)offset, textBaseline, (int)fragmentWidth, getCharHeight(g), font); } // 2. Waved effect if (attributes.isWaved()) { if (attributes.getWaveColor() != null) { g.setColor(attributes.getWaveColor()); } EffectPainter.WAVE_UNDERSCORE.paint(g, (int)offset, textBaseline + 1, (int)fragmentWidth, Math.max(2, metrics.getDescent()), font); } // 3. Underline if (attributes.isUnderline()) { EffectPainter.LINE_UNDERSCORE.paint(g, (int)offset, textBaseline, (int)fragmentWidth, metrics.getDescent(), font); } // 4. Bold Dotted Line if (attributes.isBoldDottedLine()) { final int dottedAt = SystemInfo.isMac ? textBaseline : textBaseline + 1; final Color lineColor = attributes.getWaveColor(); UIUtil.drawBoldDottedLine(g, (int)offset, (int)(offset + fragmentWidth), dottedAt, bgColor, lineColor, isOpaque()); } if (attributes.isSearchMatch()) { searchMatches.add(new Object[]{offset, offset + fragmentWidth, (float)textBaseline, myFragments.get(i), g.getFont(), attributes}); } offset = endOffset; i++; } // Paint focus border around the text and icon (if necessary) if (myPaintFocusBorder && myBorder != null) { if (focusAroundIcon) { myBorder.paintBorder(this, g, 0, 0, getWidth(), getHeight()); } else { int textStart = 0; // Skip all icons that occur before any text. for (PositionedIcon positionedIcon : myIcons) { if (positionedIcon.index != 0) { break; } textStart += positionedIcon.icon.getIconWidth() + myIconTextGap; } myBorder.paintBorder(this, g, textStart, 0, getWidth() - textStart, getHeight()); } } // draw search matches after all for (final Object[] info : searchMatches) { final float x1 = (float)info[0]; final float x2 = (float)info[1]; UIUtil.drawSearchMatch(g, x1, x2, getHeight()); g.setFont((Font)info[4]); final float baseline = (float)info[2]; final String text = (String)info[3]; if (shouldDrawMacShadow()) { g.setColor(SHADOW_COLOR); g.drawString(text, x1, baseline + 1); } g.setColor(new JBColor(Gray._50, Gray._0)); g.drawString(text, x1, baseline); if (((SimpleTextAttributes)info[5]).isStrikeout()) { EffectPainter.STRIKE_THROUGH.paint(g, (int)x1, (int)baseline, (int)(x2 - x1), getCharHeight(g), g.getFont()); } } return (int)offset; } private static int getCharHeight(Graphics g) { // magic of determining character height return g.getFontMetrics().charWidth('a'); } private int computeTextAlignShift() { if (myTextAlign == SwingConstants.LEFT || myTextAlign == SwingConstants.LEADING) { return 0; } final int componentWidth = getSize().width; final int excessiveWidth = componentWidth - computePreferredSize(false).width; if (excessiveWidth <= 0) { return 0; } if (myTextAlign == SwingConstants.CENTER) { return excessiveWidth / 2; } else if (myTextAlign == SwingConstants.RIGHT || myTextAlign == SwingConstants.TRAILING) { return excessiveWidth; } return 0; } protected boolean shouldDrawMacShadow() { return false; } protected boolean shouldDrawDimmed() { return false; } protected boolean shouldDrawBackground() { return false; } protected void paintIcon(@NotNull Graphics g, @NotNull Icon icon, int offset) { final Rectangle area = computePaintArea(); icon.paintIcon(this, g, offset, area.y + (area.height - icon.getIconHeight() + 1) / 2); } protected void applyAdditionalHints(@NotNull Graphics2D g) { UISettings.setupAntialiasing(g); } @Override public int getBaseline(int width, int height) { super.getBaseline(width, height); return getTextBaseLine(getFontMetrics(getFont()), height); } public boolean isTransparentIconBackground() { return myTransparentIconBackground; } public void setTransparentIconBackground(boolean transparentIconBackground) { myTransparentIconBackground = transparentIconBackground; } public static int getTextBaseLine(@NotNull FontMetrics metrics, final int height) { // adding leading to ascent, just like in editor (leads to bad presentation for certain fonts with Oracle JDK, see IDEA-167541) return (height - metrics.getHeight()) / 2 + metrics.getAscent() + (SystemInfo.isJetBrainsJvm ? metrics.getLeading() : 0); } private static void checkCanPaint(Graphics g) { if (UIUtil.isPrinting(g)) return; /* wtf?? if (!isDisplayable()) { LOG.assertTrue(false, logSwingPath()); } */ final Application application = ApplicationManager.getApplication(); if (application != null) { application.assertIsDispatchThread(); } else if (!SwingUtilities.isEventDispatchThread()) { throw new RuntimeException(Thread.currentThread().toString()); } } @NotNull private String logSwingPath() { final StringBuilder buffer = new StringBuilder("Components hierarchy:\n"); for (Container c = this; c != null; c = c.getParent()) { buffer.append('\n'); buffer.append(c); } return buffer.toString(); } protected void setBorderInsets(Insets insets) { if (myBorder instanceof MyBorder) { ((MyBorder)myBorder).setInsets(insets); } revalidateAndRepaint(); } private static final class MyBorder implements Border { private Insets myInsets; public MyBorder() { myInsets = JBUI.insets(1); } public void setInsets(final Insets insets) { myInsets = insets; } @Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { } @Override public Insets getBorderInsets(final Component c) { return (Insets)myInsets.clone(); } @Override public boolean isBorderOpaque() { return false; } } @NotNull public CharSequence getCharSequence(boolean mainOnly) { final List<String> fragments = mainOnly && myMainTextLastIndex > -1 && myMainTextLastIndex + 1 < myFragments.size() ? myFragments.subList(0, myMainTextLastIndex + 1) : myFragments; return StringUtil.join(fragments, ""); } @Override public String toString() { return getCharSequence(false).toString(); } public void change(@NotNull Runnable runnable, boolean autoInvalidate) { final boolean old = myAutoInvalidate; myAutoInvalidate = autoInvalidate; try { runnable.run(); } finally { myAutoInvalidate = old; } } @Override public AccessibleContext getAccessibleContext() { if (accessibleContext == null) { accessibleContext = new AccessibleSimpleColoredComponent(); } return accessibleContext; } protected class AccessibleSimpleColoredComponent extends JComponent.AccessibleJComponent { @Override public String getAccessibleName() { return getCharSequence(false).toString(); } @Override public AccessibleRole getAccessibleRole() { return AccessibleRole.LABEL; } } public static class BrowserLauncherTag implements Runnable { private final String myUrl; public BrowserLauncherTag(@NotNull String url) { myUrl = url; } @Override public void run() { BrowserUtil.browse(myUrl); } } public interface ColoredIterator extends Iterator<String> { int getOffset(); int getEndOffset(); @NotNull String getFragment(); @NotNull SimpleTextAttributes getTextAttributes(); int split(int offset, @NotNull SimpleTextAttributes attributes); } private class MyIterator implements ColoredIterator { int myIndex = -1; int myOffset; int myEndOffset; @Override public int getOffset() { return myOffset; } @Override public int getEndOffset() { return myEndOffset; } @NotNull @Override public String getFragment() { return myFragments.get(myIndex); } @NotNull @Override public SimpleTextAttributes getTextAttributes() { return myAttributes.get(myIndex); } @Override public int split(int offset, @NotNull SimpleTextAttributes attributes) { if (offset < 0 || offset > myEndOffset - myOffset) { throw new IllegalArgumentException(offset + " is not within [0, " + (myEndOffset - myOffset) + "]"); } if (offset == myEndOffset - myOffset) { // replace myAttributes.set(myIndex, attributes); } else if (offset > 0) { // split final String text = getFragment(); myFragments.set(myIndex, text.substring(0, offset)); myAttributes.add(myIndex, attributes); myFragments.add(myIndex + 1, text.substring(offset)); if (myFragmentTags != null && myFragmentTags.size() > myIndex) { myFragmentTags.add(myIndex, myFragments.get(myIndex)); } if (myIndex < myLayouts.size()) myLayouts.set(myIndex, null); if ((myIndex + 1) < myLayouts.size()) myLayouts.add(myIndex + 1, null); myIndex++; } myOffset += offset; return myOffset; } @Override public boolean hasNext() { return myIndex + 1 < myFragments.size(); } @Override public String next() { myIndex++; myOffset = myEndOffset; final String text = getFragment(); myEndOffset += text.length(); return text; } @Override public void remove() { throw new UnsupportedOperationException(); } } }
flutter-intellij/flutter-idea/src/io/flutter/view/MultiIconSimpleColoredComponent.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/view/MultiIconSimpleColoredComponent.java", "repo_id": "flutter-intellij", "token_count": 13967 }
457
/* * 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.vmService; import org.jetbrains.annotations.Nullable; public final class ServiceExtensionState { private final boolean enabled; @Nullable private final Object value; public ServiceExtensionState(boolean enabled, @Nullable Object value) { this.enabled = enabled; this.value = value; } public boolean isEnabled() { return enabled; } @Nullable public Object getValue() { return value; } }
flutter-intellij/flutter-idea/src/io/flutter/vmService/ServiceExtensionState.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/io/flutter/vmService/ServiceExtensionState.java", "repo_id": "flutter-intellij", "token_count": 181 }
458
/* * 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 static org.apache.commons.lang3.StringUtils.join; import org.apache.commons.lang3.builder.HashCodeBuilder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * An node in the Flutter specific outline structure of a file. * * @coverage dart.server.generated.types */ @SuppressWarnings("unused") public class FlutterOutline { public static final FlutterOutline[] EMPTY_ARRAY = new FlutterOutline[0]; public static final List<FlutterOutline> EMPTY_LIST = Lists.newArrayList(); /** * The kind of the node. */ private final String kind; /** * The offset of the first character of the element. This is different than the offset in the * Element, which is the offset of the name of the element. It can be used, for example, to map * locations in the file back to an outline. */ private final int offset; /** * The length of the element. */ private final int length; /** * The offset of the first character of the element code, which is neither documentation, nor * annotation. */ private final int codeOffset; /** * The length of the element code. */ private final int codeLength; /** * The text label of the node children of the node. It is provided for any * FlutterOutlineKind.GENERIC node, where better information is not available. */ private final String label; /** * If this node is a Dart element, the description of it; omitted otherwise. */ private final Element dartElement; /** * Additional attributes for this node, which might be interesting to display on the client. These * attributes are usually arguments for the instance creation or the invocation that created the * widget. */ private final List<FlutterOutlineAttribute> attributes; /** * If the node creates a new class instance, or a reference to an instance, this field has the name * of the class. */ private final String className; /** * A short text description how this node is associated with the parent node. For example "appBar" * or "body" in Scaffold. */ private final String parentAssociationLabel; /** * If FlutterOutlineKind.VARIABLE, the name of the variable. */ private final String variableName; /** * The children of the node. The field will be omitted if the node has no children. */ private final List<FlutterOutline> children; /** * Constructor for {@link FlutterOutline}. */ public FlutterOutline(String kind, int offset, int length, int codeOffset, int codeLength, String label, Element dartElement, List<FlutterOutlineAttribute> attributes, String className, String parentAssociationLabel, String variableName, List<FlutterOutline> children) { this.kind = kind; this.offset = offset; this.length = length; this.codeOffset = codeOffset; this.codeLength = codeLength; this.label = label; this.dartElement = dartElement; this.attributes = attributes; this.className = className; this.parentAssociationLabel = parentAssociationLabel; this.variableName = variableName; this.children = children; } @Override public boolean equals(Object obj) { if (obj instanceof FlutterOutline) { final FlutterOutline other = (FlutterOutline)obj; return ObjectUtilities.equals(other.kind, kind) && other.offset == offset && other.length == length && other.codeOffset == codeOffset && other.codeLength == codeLength && ObjectUtilities.equals(other.label, label) && ObjectUtilities.equals(other.dartElement, dartElement) && ObjectUtilities.equals(other.attributes, attributes) && ObjectUtilities.equals(other.className, className) && ObjectUtilities.equals(other.parentAssociationLabel, parentAssociationLabel) && ObjectUtilities.equals(other.variableName, variableName) && ObjectUtilities.equals(other.children, children); } return false; } public static FlutterOutline fromJson(JsonObject jsonObject) { final String kind = jsonObject.get("kind").getAsString(); final int offset = jsonObject.get("offset").getAsInt(); final int length = jsonObject.get("length").getAsInt(); final int codeOffset = jsonObject.get("codeOffset").getAsInt(); final int codeLength = jsonObject.get("codeLength").getAsInt(); final String label = jsonObject.get("label") == null ? null : jsonObject.get("label").getAsString(); final Element dartElement = jsonObject.get("dartElement") == null ? null : Element.fromJson(jsonObject.get("dartElement").getAsJsonObject()); final List<FlutterOutlineAttribute> attributes = jsonObject.get("attributes") == null ? null : FlutterOutlineAttribute.fromJsonArray(jsonObject.get("attributes").getAsJsonArray()); final String className = jsonObject.get("className") == null ? null : jsonObject.get("className").getAsString(); final String parentAssociationLabel = jsonObject.get("parentAssociationLabel") == null ? null : jsonObject.get("parentAssociationLabel").getAsString(); final String variableName = jsonObject.get("variableName") == null ? null : jsonObject.get("variableName").getAsString(); final List<FlutterOutline> children = jsonObject.get("children") == null ? null : FlutterOutline.fromJsonArray(jsonObject.get("children").getAsJsonArray()); return new FlutterOutline(kind, offset, length, codeOffset, codeLength, label, dartElement, attributes, className, parentAssociationLabel, variableName, children); } public static List<FlutterOutline> fromJsonArray(JsonArray jsonArray) { if (jsonArray == null) { return EMPTY_LIST; } final ArrayList<FlutterOutline> list = new ArrayList<>(jsonArray.size()); final Iterator<JsonElement> iterator = jsonArray.iterator(); while (iterator.hasNext()) { list.add(fromJson(iterator.next().getAsJsonObject())); } return list; } /** * Additional attributes for this node, which might be interesting to display on the client. These * attributes are usually arguments for the instance creation or the invocation that created the * widget. */ public List<FlutterOutlineAttribute> getAttributes() { return attributes; } /** * The children of the node. The field will be omitted if the node has no children. */ public List<FlutterOutline> getChildren() { return children; } /** * If the node creates a new class instance, or a reference to an instance, this field has the name * of the class. */ public String getClassName() { return className; } /** * The length of the element code. */ public int getCodeLength() { return codeLength; } /** * The offset of the first character of the element code, which is neither documentation, nor * annotation. */ public int getCodeOffset() { return codeOffset; } /** * If this node is a Dart element, the description of it; omitted otherwise. */ public Element getDartElement() { return dartElement; } /** * The kind of the node. */ public String getKind() { return kind; } /** * The text label of the node children of the node. It is provided for any * FlutterOutlineKind.GENERIC node, where better information is not available. */ public String getLabel() { return label; } /** * The length of the element. */ public int getLength() { return length; } /** * The offset of the first character of the element. This is different than the offset in the * Element, which is the offset of the name of the element. It can be used, for example, to map * locations in the file back to an outline. */ public int getOffset() { return offset; } /** * A short text description how this node is associated with the parent node. For example "appBar" * or "body" in Scaffold. */ public String getParentAssociationLabel() { return parentAssociationLabel; } /** * If FlutterOutlineKind.VARIABLE, the name of the variable. */ public String getVariableName() { return variableName; } @Override public int hashCode() { final HashCodeBuilder builder = new HashCodeBuilder(); builder.append(kind); builder.append(offset); builder.append(length); builder.append(codeOffset); builder.append(codeLength); builder.append(label); builder.append(dartElement); builder.append(attributes); builder.append(className); builder.append(parentAssociationLabel); builder.append(variableName); builder.append(children); return builder.toHashCode(); } public JsonObject toJson() { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("kind", kind); jsonObject.addProperty("offset", offset); jsonObject.addProperty("length", length); jsonObject.addProperty("codeOffset", codeOffset); jsonObject.addProperty("codeLength", codeLength); if (label != null) { jsonObject.addProperty("label", label); } if (dartElement != null) { jsonObject.add("dartElement", dartElement.toJson()); } if (attributes != null) { final JsonArray jsonArrayAttributes = new JsonArray(); for (FlutterOutlineAttribute elt : attributes) { jsonArrayAttributes.add(elt.toJson()); } jsonObject.add("attributes", jsonArrayAttributes); } if (className != null) { jsonObject.addProperty("className", className); } if (parentAssociationLabel != null) { jsonObject.addProperty("parentAssociationLabel", parentAssociationLabel); } if (variableName != null) { jsonObject.addProperty("variableName", variableName); } if (children != null) { final JsonArray jsonArrayChildren = new JsonArray(); for (FlutterOutline elt : children) { jsonArrayChildren.add(elt.toJson()); } jsonObject.add("children", jsonArrayChildren); } return jsonObject; } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("["); builder.append("kind="); builder.append(kind).append(", "); builder.append("offset="); builder.append(offset).append(", "); builder.append("length="); builder.append(length).append(", "); builder.append("codeOffset="); builder.append(codeOffset).append(", "); builder.append("codeLength="); builder.append(codeLength).append(", "); builder.append("label="); builder.append(label).append(", "); builder.append("dartElement="); builder.append(dartElement).append(", "); if (attributes != null) { builder.append("attributes="); builder.append(join(attributes, ", ")).append(", "); } builder.append("className="); builder.append(className).append(", "); builder.append("parentAssociationLabel="); builder.append(parentAssociationLabel).append(", "); builder.append("variableName="); builder.append(variableName).append(", "); if (children != null) { builder.append("children="); builder.append(join(children, ", ")); } builder.append("]"); return builder.toString(); } }
flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterOutline.java/0
{ "file_path": "flutter-intellij/flutter-idea/src/org/dartlang/analysis/server/protocol/FlutterOutline.java", "repo_id": "flutter-intellij", "token_count": 4114 }
459
/* * 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.analytics; import org.junit.Before; import org.junit.Test; import java.io.PrintWriter; import java.io.StringWriter; import static org.junit.Assert.assertEquals; public class AnalyticsTest { private Analytics analytics; private MockAnalyticsTransport transport; @Before public void setUp() { transport = new MockAnalyticsTransport(); analytics = new Analytics("123e4567-e89b-12d3-a456-426655440000", "1.0", "IntelliJ CE", "2016.3.2"); analytics.setTransport(transport); analytics.setCanSend(true); } @Test public void testSendScreenView() { analytics.sendScreenView("testAnalyticsPage"); assertEquals(1, transport.sentValues.size()); } @Test public void testSendEvent() { analytics.sendEvent("flutter", "doctor"); assertEquals(1, transport.sentValues.size()); } @Test public void testSendTiming() { analytics.sendTiming("perf", "reloadTime", 100); assertEquals(1, transport.sentValues.size()); } @Test public void testSendException() { final Throwable throwable = new UnsupportedOperationException("test operation"); final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter); throwable.printStackTrace(printWriter); analytics.sendException(stringWriter.toString().trim(), true); assertEquals(1, transport.sentValues.size()); } @Test public void testOptOutDoesntSend() { analytics.setCanSend(false); analytics.sendScreenView("testAnalyticsPage"); assertEquals(0, transport.sentValues.size()); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/analytics/AnalyticsTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/analytics/AnalyticsTest.java", "repo_id": "flutter-intellij", "token_count": 568 }
460
/* * 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.editor; import com.intellij.codeInsight.daemon.LineMarkerInfo; import com.intellij.psi.PsiElement; import com.intellij.psi.impl.source.tree.LeafPsiElement; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartNewExpression; import com.jetbrains.lang.dart.psi.DartReferenceExpression; import io.flutter.dart.DartSyntax; import io.flutter.sdk.FlutterSdk; import io.flutter.sdk.FlutterSdkVersion; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @SuppressWarnings("ALL") public class FlutterIconLineMarkerTest extends io.flutter.ide.FlutterCodeInsightFixtureTestCase { private FlutterSdk getSdk() { final FlutterSdk mockSdk = mock(FlutterSdk.class); String sdkPath = getSdkPath(); when(mockSdk.getHomePath()).thenReturn(sdkPath); when(mockSdk.getVersion()).thenReturn(FlutterSdkVersion.DISTRIBUTED_ICONS); return mockSdk; } private String getSdkPath() { String sdk = System.getenv("FLUTTER_SDK"); if (sdk == null) sdk = System.getProperty("flutter.sdk"); return sdk == null ? "testData/sdk" : sdk; // This constant is not usable, but used to be the root of a stripped-down Flutter SDK } @Test public void testLocatesIconsReference() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { Icons.access_alarm; }", "Icons", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartReferenceExpression element = DartSyntax.findEnclosingReferenceExpression(testIdentifier); assertNotNull(element); } @Test public void testLocatesIconCtor() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { IconData(0xe190, fontFamily: 'MaterialIcons'); }", "IconData", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartCallExpression element = DartSyntax.findEnclosingFunctionCall(testIdentifier, "IconData"); assertNotNull(element); } // //@Test @Ignore("file not found") //public void testLocatesCupertinoIconCtor() throws Exception { // final PsiElement testIdentifier = // setUpDartElement("main() { IconData(0xe190, fontFamily: 'CupertinoIcons'); }", "IconData", LeafPsiElement.class); // final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); // assertNotNull(marker); // final DartCallExpression element = DartSyntax.findEnclosingFunctionCall(testIdentifier, "IconData"); // assertNotNull(element); //} @Test public void testLocatesConstIconCtor() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { const IconData(0xe190, fontFamily: 'MaterialIcons'); }", "IconData", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartNewExpression element = DartSyntax.findEnclosingNewExpression(testIdentifier); assertNotNull(element); } @Test public void testLocatesCupertinoIconsReference() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { CupertinoIcons.book; }", "CupertinoIcons", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartReferenceExpression element = DartSyntax.findEnclosingReferenceExpression(testIdentifier); assertNotNull(element); } @Test public void testLocatesCupertinoIconsReferenceWithComment() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { CupertinoIcons . /* a book */ book; }", "CupertinoIcons", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartReferenceExpression element = DartSyntax.findEnclosingReferenceExpression(testIdentifier); assertNotNull(element); } @Test public void locatesIconCtorWithWhitespace() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { IconData ( 0xe190 ); }", "IconData", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartCallExpression element = DartSyntax.findEnclosingFunctionCall(testIdentifier, "IconData"); assertNotNull(element); } @Test public void locatesConstIconCtorWithLineEndComment() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { const IconData // comment\n ( 0xe190, fontFamily: 'MaterialIcons'); }", "IconData", LeafPsiElement.class); final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); assertNotNull(marker); final DartNewExpression element = DartSyntax.findEnclosingNewExpression(testIdentifier); assertNotNull(element); } @Test public void allowsNullIconData() throws Exception { final PsiElement testIdentifier = setUpDartElement("main() { final x = IconData(null); }", "IconData", LeafPsiElement.class); try { final LineMarkerInfo<?> marker = new FlutterIconLineMarkerProvider().getLineMarkerInfo(testIdentifier, getSdk()); } catch (NumberFormatException ex) { fail(ex.getMessage()); } } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/FlutterIconLineMarkerTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/editor/FlutterIconLineMarkerTest.java", "repo_id": "flutter-intellij", "token_count": 1991 }
461
/* * 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.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.jetbrains.annotations.Nullable; import org.junit.Before; import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.*; public class MainFileTest { @Rule public final ProjectFixture fixture = Testing.makeCodeInsightModule(); @Rule public final TestDir tmp = new TestDir(); VirtualFile contentRoot; String appDir; @Before public void setUp() throws Exception { contentRoot = tmp.ensureDir("root"); appDir = tmp.ensureDir("root/work").getPath(); tmp.writeFile("root/work/pubspec.yaml", ""); tmp.ensureDir("root/work/lib"); Testing.runOnDispatchThread( () -> ModuleRootModificationUtil.addContentRoot(fixture.getModule(), contentRoot.getPath())); } @Test @Ignore public void shouldFindAppDirForValidFlutterApp() throws Exception { final String mainPath = tmp.writeFile("root/work/lib/main.dart", "import \"package:flutter/ui.dart\"\n" + "main() {}\n").getPath(); final MainFile.Result result = Testing.computeOnDispatchThread(() -> MainFile.verify(mainPath, fixture.getProject())); if (!result.canLaunch()) { fail("Flutter app should be valid but got error: " + result.getError()); } final MainFile main = result.get(); assertEquals(mainPath, main.getFile().getPath()); assertEquals(appDir, main.getAppDir().getPath()); assertTrue(main.hasFlutterImports()); } @Test @Ignore public void shouldDetectErrors() throws Exception { checkInvalid(null, "hasn't been set"); checkInvalid("notfound.dart", "not found"); tmp.writeFile("root/foo.txt", ""); checkInvalid("root/foo.txt", "not a Dart file"); tmp.writeFile("root/foo.dart", ""); checkInvalid("root/foo.dart", "doesn't contain a main function"); tmp.writeFile("elsewhere.dart", "import \"package:flutter/ui.dart\"\n" + "main() {}\n"); checkInvalid("elsewhere.dart", "isn't within the current project"); tmp.writeFile("root/elsewhere.dart", "import \"package:flutter/ui.dart\"\n" + "main() {}\n"); checkInvalid("root/elsewhere.dart", "isn't within a Flutter application"); } private void checkInvalid(@Nullable String path, String expected) throws Exception { final String fullPath = path == null ? null : tmp.pathAt(path); final MainFile.Result main = Testing.computeOnDispatchThread( () -> MainFile.verify(fullPath, fixture.getProject())); assertFalse(main.canLaunch()); if (main.getError().contains("{0}")) { fail("bad error message: " + main.getError()); } if (!main.getError().contains(expected)) { fail("expected error to contain '" + expected + "' but got: " + main.getError()); } } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/MainFileTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/run/MainFileTest.java", "repo_id": "flutter-intellij", "token_count": 1213 }
462
/* * 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.sdk; import org.junit.Test; import static org.junit.Assert.*; public class FlutterSdkVersionTest { @Test public void parsesGoodVersion() { final FlutterSdkVersion version = new FlutterSdkVersion("0.0.12"); assertTrue(version.isValid()); } @Test public void trackWidgetCreationRecommendedRange() { assertFalse(new FlutterSdkVersion("0.0.12").isTrackWidgetCreationRecommended()); assertFalse(new FlutterSdkVersion("0.10.1").isTrackWidgetCreationRecommended()); assertFalse(new FlutterSdkVersion("0.10.1.pre").isTrackWidgetCreationRecommended()); assertFalse(new FlutterSdkVersion("0.10.1.pre").isTrackWidgetCreationRecommended()); assertTrue(new FlutterSdkVersion( "0.10.2.pre.1").isTrackWidgetCreationRecommended()); assertTrue(new FlutterSdkVersion( "0.10.2-pre.121").isTrackWidgetCreationRecommended()); assertTrue(new FlutterSdkVersion( "0.10.2").isTrackWidgetCreationRecommended()); assertTrue(new FlutterSdkVersion( "0.10.3").isTrackWidgetCreationRecommended()); assertTrue(new FlutterSdkVersion( "1.0.0").isTrackWidgetCreationRecommended()); assertFalse(new FlutterSdkVersion( "unknown").isTrackWidgetCreationRecommended()); } @Test public void handlesBadVersion() { final FlutterSdkVersion version = new FlutterSdkVersion("unknown"); assertFalse(version.isValid()); } @Test public void comparesBetaVersions() { assertEquals( new FlutterSdkVersion("1.0.0").compareTo(new FlutterSdkVersion("1.0.1")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0").compareTo(new FlutterSdkVersion("1.0.0")), 0 ); assertEquals( new FlutterSdkVersion("1.0.1").compareTo(new FlutterSdkVersion("1.0.0")), 1 ); // Stable version is ahead of all beta versions with the same major/minor/patch numbers. assertEquals( new FlutterSdkVersion("1.0.0").compareTo(new FlutterSdkVersion("1.0.0-1.0.pre")), 1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0-1.0.pre")), 1 ); assertEquals( new FlutterSdkVersion("1.0.0-2.0.pre").compareTo(new FlutterSdkVersion("1.0.0-1.0.pre")), 1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0-1.2.pre")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0-2.1.pre")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre")), 0 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre.123").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre.123")), 0 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre.123").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre.124")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre.124").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre.123")), 1 ); // Master versions will be aware of the latest preceding dev version and have a version number higher than the preceding dev version. // e.g. the next commit to master after cutting dev version 2.0.0-2.0.pre would be 2.0.0-3.0.pre.1, with the number 1 signifying 1 // commit after the previous version. assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre.123").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre")), -1 ); assertEquals( new FlutterSdkVersion("1.0.0-1.1.pre").compareTo(new FlutterSdkVersion("1.0.0-1.1.pre.123")), 1 ); assertEquals( new FlutterSdkVersion("1.0.0-2.0.pre.123").compareTo(new FlutterSdkVersion("1.0.0-1.0.pre")), 1 ); assertEquals( new FlutterSdkVersion("1.0.0-2.0.pre").compareTo(new FlutterSdkVersion("1.0.0-1.0.pre.123")), 1 ); } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/sdk/FlutterSdkVersionTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/sdk/FlutterSdkVersionTest.java", "repo_id": "flutter-intellij", "token_count": 1780 }
463
/* * 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.utils; import com.google.common.util.concurrent.Uninterruptibles; import org.junit.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; public class ThreadUtilTest { @Test public void simple() { final CountDownLatch stopLatch = new CountDownLatch(1); try { final Thread newThread = new Thread(() -> Uninterruptibles.awaitUninterruptibly(stopLatch)); newThread.start(); final List<Thread> withNewThread = ThreadUtil.getCurrentGroupThreads(); assertThat(withNewThread, hasItem(newThread)); // Ask the new thread to stop and wait for it. stopLatch.countDown(); for (int i = 0; i < 1000; i++) { if (!newThread.isAlive()) { break; } Uninterruptibles.sleepUninterruptibly(10, TimeUnit.MILLISECONDS); } final List<Thread> withoutNewThread = ThreadUtil.getCurrentGroupThreads(); assertThat(withoutNewThread, not(hasItem(newThread))); } finally { stopLatch.countDown(); } } }
flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/ThreadUtilTest.java/0
{ "file_path": "flutter-intellij/flutter-idea/testSrc/unit/io/flutter/utils/ThreadUtilTest.java", "repo_id": "flutter-intellij", "token_count": 509 }
464
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonArray; import com.google.gson.JsonObject; /** * A {@link ClassObj} provides information about a Dart language class. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class ClassObj extends Obj { public ClassObj(JsonObject json) { super(json); } /** * The error which occurred during class finalization, if it exists. * * Can return <code>null</code>. */ public ErrorRef getError() { JsonObject obj = (JsonObject) json.get("error"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ErrorRef(obj); } /** * A list of fields in this class. Does not include fields from superclasses. */ public ElementList<FieldRef> getFields() { return new ElementList<FieldRef>(json.get("fields").getAsJsonArray()) { @Override protected FieldRef basicGet(JsonArray array, int index) { return new FieldRef(array.get(index).getAsJsonObject()); } }; } /** * A list of functions in this class. Does not include functions from superclasses. */ public ElementList<FuncRef> getFunctions() { return new ElementList<FuncRef>(json.get("functions").getAsJsonArray()) { @Override protected FuncRef basicGet(JsonArray array, int index) { return new FuncRef(array.get(index).getAsJsonObject()); } }; } /** * A list of interface types for this class. * * The values will be of the kind: Type. */ public ElementList<InstanceRef> getInterfaces() { return new ElementList<InstanceRef>(json.get("interfaces").getAsJsonArray()) { @Override protected InstanceRef basicGet(JsonArray array, int index) { return new InstanceRef(array.get(index).getAsJsonObject()); } }; } /** * Is this a base class? */ public boolean getIsBaseClass() { return getAsBoolean("isBaseClass"); } /** * Is this a final class? */ public boolean getIsFinal() { return getAsBoolean("isFinal"); } /** * Is this an interface class? */ public boolean getIsInterfaceClass() { return getAsBoolean("isInterfaceClass"); } /** * Is this a mixin class? */ public boolean getIsMixinClass() { return getAsBoolean("isMixinClass"); } /** * Is this a sealed class? */ public boolean getIsSealed() { return getAsBoolean("isSealed"); } /** * The library which contains this class. */ public LibraryRef getLibrary() { return new LibraryRef((JsonObject) json.get("library")); } /** * The location of this class in the source code. * * Can return <code>null</code>. */ public SourceLocation getLocation() { JsonObject obj = (JsonObject) json.get("location"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new SourceLocation(obj); } /** * The mixin type for this class, if any. * * The value will be of the kind: Type. * * Can return <code>null</code>. */ public InstanceRef getMixin() { JsonObject obj = (JsonObject) json.get("mixin"); if (obj == null) return null; return new InstanceRef(obj); } /** * The name of this class. */ public String getName() { return getAsString("name"); } /** * A list of subclasses of this class. */ public ElementList<ClassRef> getSubclasses() { return new ElementList<ClassRef>(json.get("subclasses").getAsJsonArray()) { @Override protected ClassRef basicGet(JsonArray array, int index) { return new ClassRef(array.get(index).getAsJsonObject()); } }; } /** * The superclass of this class, if any. * * Can return <code>null</code>. */ public ClassRef getSuperClass() { JsonObject obj = (JsonObject) json.get("super"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ClassRef(obj); } /** * The supertype for this class, if any. * * The value will be of the kind: Type. * * Can return <code>null</code>. */ public InstanceRef getSuperType() { JsonObject obj = (JsonObject) json.get("superType"); if (obj == null) return null; return new InstanceRef(obj); } /** * Are allocations of this class being traced? */ public boolean getTraceAllocations() { return getAsBoolean("traceAllocations"); } /** * The type parameters for the class. * * Provided if the class is generic. * * Can return <code>null</code>. */ public ElementList<InstanceRef> getTypeParameters() { if (json.get("typeParameters") == null) return null; return new ElementList<InstanceRef>(json.get("typeParameters").getAsJsonArray()) { @Override protected InstanceRef basicGet(JsonArray array, int index) { return new InstanceRef(array.get(index).getAsJsonObject()); } }; } /** * Is this an abstract class? */ public boolean isAbstract() { return getAsBoolean("abstract"); } /** * Is this a const class? */ public boolean isConst() { return getAsBoolean("const"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ClassObj.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ClassObj.java", "repo_id": "flutter-intellij", "token_count": 2247 }
465
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * An {@link ErrorObj} represents a Dart language level error. This is distinct from an RPC error. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class ErrorObj extends Obj { public ErrorObj(JsonObject json) { super(json); } /** * If this error is due to an unhandled exception, this is the exception thrown. * * Can return <code>null</code>. */ public InstanceRef getException() { JsonObject obj = (JsonObject) json.get("exception"); if (obj == null) return null; return new InstanceRef(obj); } /** * What kind of error is this? */ public ErrorKind getKind() { final JsonElement value = json.get("kind"); try { return value == null ? ErrorKind.Unknown : ErrorKind.valueOf(value.getAsString()); } catch (IllegalArgumentException e) { return ErrorKind.Unknown; } } /** * A description of the error. */ public String getMessage() { return getAsString("message"); } /** * If this error is due to an unhandled exception, this is the stacktrace object. * * Can return <code>null</code>. */ public InstanceRef getStacktrace() { JsonObject obj = (JsonObject) json.get("stacktrace"); if (obj == null) return null; return new InstanceRef(obj); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ErrorObj.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/ErrorObj.java", "repo_id": "flutter-intellij", "token_count": 666 }
466
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; /** * An {@link Instance} represents an instance of the Dart language class {@link Obj}. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class Instance extends Obj { public Instance(JsonObject json) { super(json); } /** * The stack trace associated with the allocation of a ReceivePort. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public InstanceRef getAllocationLocation() { JsonObject obj = (JsonObject) json.get("allocationLocation"); if (obj == null) return null; return new InstanceRef(obj); } /** * The elements of a Map instance. * * Provided for instance kinds: * - Map * * Can return <code>null</code>. */ public ElementList<MapAssociation> getAssociations() { if (json.get("associations") == null) return null; return new ElementList<MapAssociation>(json.get("associations").getAsJsonArray()) { @Override protected MapAssociation basicGet(JsonArray array, int index) { return new MapAssociation(array.get(index).getAsJsonObject()); } }; } /** * The bound of a TypeParameter or BoundedType. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. * * Provided for instance kinds: * - BoundedType * - TypeParameter * * Can return <code>null</code>. */ public InstanceRef getBound() { JsonObject obj = (JsonObject) json.get("bound"); if (obj == null) return null; return new InstanceRef(obj); } /** * The bytes of a TypedData instance. * * The data is provided as a Base64 encoded string. * * Provided for instance kinds: * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public String getBytes() { return getAsString("bytes"); } /** * Instance references always include their class. */ @Override public ClassRef getClassRef() { return new ClassRef((JsonObject) json.get("class")); } /** * The context associated with a Closure instance. * * Provided for instance kinds: * - Closure * * Can return <code>null</code>. */ public ContextRef getClosureContext() { JsonObject obj = (JsonObject) json.get("closureContext"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ContextRef(obj); } /** * The function associated with a Closure instance. * * Provided for instance kinds: * - Closure * * Can return <code>null</code>. */ public FuncRef getClosureFunction() { JsonObject obj = (JsonObject) json.get("closureFunction"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new FuncRef(obj); } /** * The number of elements or associations or codeunits returned. This is only provided when it is * less than length. * * Provided for instance kinds: * - String * - List * - Map * - Set * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public int getCount() { return getAsInt("count"); } /** * A name associated with a ReceivePort used for debugging purposes. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public String getDebugName() { return getAsString("debugName"); } /** * The elements of a List or Set instance. * * Provided for instance kinds: * - List * - Set * * @return one of <code>ElementList<InstanceRef></code> or <code>ElementList<Sentinel></code> * * Can return <code>null</code>. */ public ElementList<InstanceRef> getElements() { if (json.get("elements") == null) return null; return new ElementList<InstanceRef>(json.get("elements").getAsJsonArray()) { @Override protected InstanceRef basicGet(JsonArray array, int index) { return new InstanceRef(array.get(index).getAsJsonObject()); } }; } /** * The (non-static) fields of this Instance. * * Provided for instance kinds: * - PlainInstance * - Record * * Can return <code>null</code>. */ public ElementList<BoundField> getFields() { if (json.get("fields") == null) return null; return new ElementList<BoundField>(json.get("fields").getAsJsonArray()) { @Override protected BoundField basicGet(JsonArray array, int index) { return new BoundField(array.get(index).getAsJsonObject()); } }; } /** * The identityHashCode assigned to the allocated object. This hash code is the same as the hash * code provided in HeapSnapshot and CpuSample's returned by getAllocationTraces(). */ public int getIdentityHashCode() { return getAsInt("identityHashCode"); } /** * Whether this regular expression is case sensitive. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public boolean getIsCaseSensitive() { return getAsBoolean("isCaseSensitive"); } /** * Whether this regular expression matches multiple lines. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public boolean getIsMultiLine() { return getAsBoolean("isMultiLine"); } /** * What kind of instance is this? */ public InstanceKind getKind() { final JsonElement value = json.get("kind"); try { return value == null ? InstanceKind.Unknown : InstanceKind.valueOf(value.getAsString()); } catch (IllegalArgumentException e) { return InstanceKind.Unknown; } } /** * The number of (non-static) fields of a PlainInstance, or the length of a List, or the number * of associations in a Map, or the number of codeunits in a String, or the total number of * fields (positional and named) in a Record. * * Provided for instance kinds: * - PlainInstance * - String * - List * - Map * - Set * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * - Record * * Can return <code>null</code>. */ public int getLength() { return getAsInt("length"); } /** * The referent of a MirrorReference instance. * * Provided for instance kinds: * - MirrorReference * * Can return <code>null</code>. */ public ObjRef getMirrorReferent() { JsonObject obj = (JsonObject) json.get("mirrorReferent"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ObjRef(obj); } /** * The name of a Type instance. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public String getName() { return getAsString("name"); } /** * The index of the first element or association or codeunit returned. This is only provided when * it is non-zero. * * Provided for instance kinds: * - String * - List * - Map * - Set * - Uint8ClampedList * - Uint8List * - Uint16List * - Uint32List * - Uint64List * - Int8List * - Int16List * - Int32List * - Int64List * - Float32List * - Float64List * - Int32x4List * - Float32x4List * - Float64x2List * * Can return <code>null</code>. */ public int getOffset() { return getAsInt("offset"); } /** * The index of a TypeParameter instance. * * Provided for instance kinds: * - TypeParameter * * Can return <code>null</code>. */ public int getParameterIndex() { return getAsInt("parameterIndex"); } /** * The parameterized class of a type parameter: * * Provided for instance kinds: * - TypeParameter * * Can return <code>null</code>. */ public ClassRef getParameterizedClass() { JsonObject obj = (JsonObject) json.get("parameterizedClass"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ClassRef(obj); } /** * The list of parameter types for a function. * * Provided for instance kinds: * - FunctionType * * Can return <code>null</code>. */ public ElementList<Parameter> getParameters() { if (json.get("parameters") == null) return null; return new ElementList<Parameter>(json.get("parameters").getAsJsonArray()) { @Override protected Parameter basicGet(JsonArray array, int index) { return new Parameter(array.get(index).getAsJsonObject()); } }; } /** * The pattern of a RegExp instance. * * Provided for instance kinds: * - RegExp * * Can return <code>null</code>. */ public InstanceRef getPattern() { JsonObject obj = (JsonObject) json.get("pattern"); if (obj == null) return null; return new InstanceRef(obj); } /** * The port ID for a ReceivePort. * * Provided for instance kinds: * - ReceivePort * * Can return <code>null</code>. */ public int getPortId() { return getAsInt("portId"); } /** * The key for a WeakProperty instance. * * Provided for instance kinds: * - WeakProperty * * Can return <code>null</code>. */ public ObjRef getPropertyKey() { JsonObject obj = (JsonObject) json.get("propertyKey"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ObjRef(obj); } /** * The key for a WeakProperty instance. * * Provided for instance kinds: * - WeakProperty * * Can return <code>null</code>. */ public ObjRef getPropertyValue() { JsonObject obj = (JsonObject) json.get("propertyValue"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ObjRef(obj); } /** * The return type of a function. * * Provided for instance kinds: * - FunctionType * * Can return <code>null</code>. */ public InstanceRef getReturnType() { JsonObject obj = (JsonObject) json.get("returnType"); if (obj == null) return null; return new InstanceRef(obj); } /** * The target for a WeakReference instance. * * Provided for instance kinds: * - WeakReference * * Can return <code>null</code>. */ public ObjRef getTarget() { JsonObject obj = (JsonObject) json.get("target"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ObjRef(obj); } /** * The type bounded by a BoundedType instance - or - the referent of a TypeRef instance. * * The value will always be of one of the kinds: Type, TypeRef, TypeParameter, BoundedType. * * Provided for instance kinds: * - BoundedType * - TypeRef * * Can return <code>null</code>. */ public InstanceRef getTargetType() { JsonObject obj = (JsonObject) json.get("targetType"); if (obj == null) return null; return new InstanceRef(obj); } /** * The type arguments for this type. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public TypeArgumentsRef getTypeArguments() { JsonObject obj = (JsonObject) json.get("typeArguments"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new TypeArgumentsRef(obj); } /** * The corresponding Class if this Type is canonical. * * Provided for instance kinds: * - Type * * Can return <code>null</code>. */ public ClassRef getTypeClass() { JsonObject obj = (JsonObject) json.get("typeClass"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ClassRef(obj); } /** * The type parameters for a function. * * Provided for instance kinds: * - FunctionType * * Can return <code>null</code>. */ public ElementList<InstanceRef> getTypeParameters() { if (json.get("typeParameters") == null) return null; return new ElementList<InstanceRef>(json.get("typeParameters").getAsJsonArray()) { @Override protected InstanceRef basicGet(JsonArray array, int index) { return new InstanceRef(array.get(index).getAsJsonObject()); } }; } /** * The value of this instance as a string. * * Provided for the instance kinds: * - Bool (true or false) * - Double (suitable for passing to Double.parse()) * - Int (suitable for passing to int.parse()) * - String (value may be truncated) * - StackTrace * * Can return <code>null</code>. */ public String getValueAsString() { return getAsString("valueAsString"); } /** * The valueAsString for String references may be truncated. If so, this property is added with * the value 'true'. * * New code should use 'length' and 'count' instead. * * Can return <code>null</code>. */ public boolean getValueAsStringIsTruncated() { final JsonElement elem = json.get("valueAsStringIsTruncated"); return elem != null ? elem.getAsBoolean() : false; } /** * Returns whether this instance represents null. */ public boolean isNull() { return getKind() == InstanceKind.Null; } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Instance.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/Instance.java", "repo_id": "flutter-intellij", "token_count": 5949 }
467
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonObject; /** * A {@link NativeFunction} object is used to represent native functions in profiler samples. See * CpuSamples; */ @SuppressWarnings({"WeakerAccess", "unused"}) public class NativeFunction extends Element { public NativeFunction(JsonObject json) { super(json); } /** * The name of the native function this object represents. */ public String getName() { return getAsString("name"); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/NativeFunction.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/NativeFunction.java", "repo_id": "flutter-intellij", "token_count": 340 }
468
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.element; // This file is generated by the script: pkg/vm_service/tool/generate.dart in dart-lang/sdk. import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; /** * See RetainingPath. */ @SuppressWarnings({"WeakerAccess", "unused"}) public class RetainingObject extends Element { public RetainingObject(JsonObject json) { super(json); } /** * If `value` is a non-List, non-Map object, `parentField` is the name of the field containing * the previous object on the retaining path. * * @return one of <code>String</code> or <code>int</code> * * Can return <code>null</code>. */ public Object getParentField() { final JsonElement elem = json.get("parentField"); if (elem == null) return null; if (elem.isJsonPrimitive()) { final JsonPrimitive p = (JsonPrimitive) elem; if (p.isString()) return p.getAsString(); if (p.isNumber()) return p.getAsInt(); } return null; } /** * If `value` is a List, `parentListIndex` is the index where the previous object on the * retaining path is located (deprecated). * * Note: this property is deprecated and will be replaced by `parentField`. * * Can return <code>null</code>. */ public int getParentListIndex() { return getAsInt("parentListIndex"); } /** * If `value` is a Map, `parentMapKey` is the key mapping to the previous object on the retaining * path. * * Can return <code>null</code>. */ public ObjRef getParentMapKey() { JsonObject obj = (JsonObject) json.get("parentMapKey"); if (obj == null) return null; final String type = json.get("type").getAsString(); if ("Instance".equals(type) || "@Instance".equals(type)) { final String kind = json.get("kind").getAsString(); if ("Null".equals(kind)) return null; } return new ObjRef(obj); } /** * An object that is part of a retaining path. */ public ObjRef getValue() { return new ObjRef((JsonObject) json.get("value")); } }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RetainingObject.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/element/RetainingObject.java", "repo_id": "flutter-intellij", "token_count": 891 }
469
/* * Copyright (c) 2015, the Dart project authors. * * Licensed under the Eclipse Public License v1.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.eclipse.org/legal/epl-v10.html * * 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 org.dartlang.vm.service.internal; /** * JSON constants used when communicating with the VM observatory service. */ public interface VmServiceConst { static final String CODE = "code"; static final String ERROR = "error"; static final String EVENT = "event"; static final String ID = "id"; static final String MESSAGE = "message"; static final String METHOD = "method"; static final String PARAMS = "params"; static final String RESULT = "result"; static final String STREAM_ID = "streamId"; static final String TYPE = "type"; static final String JSONRPC = "jsonrpc"; static final String JSONRPC_VERSION = "2.0"; static final String DATA = "data"; /** * Parse error Invalid JSON was received by the server. * An error occurred on the server while parsing the JSON text. */ static final int PARSE_ERROR = -32700; /** * Invalid Request The JSON sent is not a valid Request object. */ static final int INVALID_REQUEST = -32600; /** * Method not found The method does not exist / is not available. */ static final int METHOD_NOT_FOUND = -32601; /** * Invalid params Invalid method parameter(s). */ static final int INVALID_PARAMS = -32602; /** * Server error Reserved for implementation-defined server-errors. * -32000 to -32099 */ static final int SERVER_ERROR = -32000; }
flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/VmServiceConst.java/0
{ "file_path": "flutter-intellij/flutter-idea/third_party/vmServiceDrivers/org/dartlang/vm/service/internal/VmServiceConst.java", "repo_id": "flutter-intellij", "token_count": 564 }
470