Repository: dart-lang/dart-samples Branch: master Commit: 3969c54f98ad Files: 212 Total size: 720.9 KB Directory structure: gitextract_3hosw9ju/ ├── .gitignore ├── LICENSE ├── README.md ├── dart_io_mini_samples/ │ ├── AUTHORS │ ├── LICENSE │ ├── README.md │ ├── example/ │ │ ├── common.css │ │ ├── files_directories_and_symlinks/ │ │ │ ├── deleting_a_file_directory_or_symlink.dart │ │ │ ├── directories/ │ │ │ │ ├── creating_a_directory.dart │ │ │ │ ├── creating_a_temporary_directory.dart │ │ │ │ └── listing_the_contents_of_a_directory.dart │ │ │ ├── file.txt │ │ │ ├── files/ │ │ │ │ ├── creating_a_file.dart │ │ │ │ ├── handling_errors_when_reading_a_file.dart │ │ │ │ ├── reading_a_file_as_a_string.dart │ │ │ │ ├── reading_a_file_as_bytes.dart │ │ │ │ ├── reading_a_file_as_lines.dart │ │ │ │ ├── reading_a_file_using_a_stream.dart │ │ │ │ ├── writing_a_string_to_a_file.dart │ │ │ │ ├── writing_bytes_to_a_file.dart │ │ │ │ └── writing_to_a_file_using_a_stream.dart │ │ │ ├── finding_the_type_of_a_filesystem_object.dart │ │ │ ├── getting_the_parent_directory.dart │ │ │ ├── renaming_a_file_directory_or_symlink.dart │ │ │ └── symlinks/ │ │ │ ├── checking_if_a_path_represents_a_symlink.dart │ │ │ ├── creating_a_symlink.dart │ │ │ └── getting_the_target_of_a_link.dart │ │ ├── http/ │ │ │ ├── adding_custom_headers.dart │ │ │ ├── getting_redirection_history.dart │ │ │ ├── getting_the_response_content_in_binary_format.dart │ │ │ ├── getting_the_response_headers.dart │ │ │ ├── handling_an_httprequest_error.dart │ │ │ ├── making_a_get_request.dart │ │ │ ├── making_a_post_request.dart │ │ │ ├── making_multiple_requests_to_the_same_server.dart │ │ │ └── reading_the_response_body.dart │ │ ├── http_server/ │ │ │ ├── implementing_a_Hello_World_http_server.dart │ │ │ ├── routing_requests_based_on_url_patterns.dart │ │ │ └── web/ │ │ │ ├── foo.html │ │ │ └── index.html │ │ ├── interacting_with_processes/ │ │ │ ├── obtaining_the_exit_code_when_running_a_process.dart │ │ │ └── running_a_process.dart │ │ ├── introduction.md │ │ ├── other_resources.md │ │ ├── paths/ │ │ │ ├── calculating_relative_paths.dart │ │ │ ├── converting_between_a_uri_and_a_path.dart │ │ │ ├── getting_information_about_a_file_path.dart │ │ │ ├── getting_the_path_separator_for_the_current_platform.dart │ │ │ ├── joining_paths.dart │ │ │ └── parsing_a_path_into_components.dart │ │ ├── platform/ │ │ │ ├── getting_environment_variables.dart │ │ │ ├── getting_information_about_the_script_being_run.dart │ │ │ └── identifying_the_operating_system.dart │ │ ├── sockets/ │ │ │ ├── using_serversockets_client.dart │ │ │ └── using_serversockets_server.dart │ │ └── websockets/ │ │ ├── using_websockets_client.dart │ │ └── using_websockets_server.dart │ ├── generate_md_for_dartlang.dart │ ├── pubspec.yaml │ └── runtests.sh ├── deferred_loading_samples/ │ ├── README.md │ ├── deferred_loading_example/ │ │ ├── README.md │ │ ├── bin/ │ │ │ └── main.dart │ │ ├── lib/ │ │ │ └── hello.dart │ │ └── pubspec.yaml │ └── lazyloader/ │ ├── README.md │ ├── lib/ │ │ ├── breakfast.dart │ │ ├── dinner.dart │ │ └── lunch.dart │ ├── pubspec.yaml │ └── web/ │ ├── index.html │ ├── main.dart │ └── styles.css ├── html5/ │ ├── AUTHORS │ ├── README.md │ ├── pubspec.yaml │ ├── tool/ │ │ └── hop_runner.dart │ └── web/ │ ├── appcache/ │ │ └── beginner/ │ │ ├── README.md │ │ ├── appcache.css │ │ ├── appcache.dart │ │ ├── appcache.mf │ │ ├── index.html │ │ └── offline.html │ ├── canvas/ │ │ ├── hidpi/ │ │ │ ├── hidpi.css │ │ │ ├── hidpi.dart │ │ │ └── hidpi.html │ │ └── imagefilters/ │ │ ├── README.md │ │ ├── imagefilters.css │ │ ├── imagefilters.dart │ │ └── index.html │ ├── dnd/ │ │ └── basics/ │ │ ├── README.md │ │ ├── basics.css │ │ ├── basics.dart │ │ └── index.html │ ├── file/ │ │ ├── dndfiles/ │ │ │ ├── README.md │ │ │ ├── dndfiles.css │ │ │ ├── dndfiles.dart │ │ │ ├── dndfiles.html │ │ │ ├── index.html │ │ │ ├── monitoring.dart │ │ │ ├── monitoring.html │ │ │ ├── slicing.dart │ │ │ └── slicing.html │ │ ├── filesystem/ │ │ │ ├── README.md │ │ │ ├── filesystem.css │ │ │ ├── filesystem.dart │ │ │ └── index.html │ │ └── terminal/ │ │ ├── README.md │ │ ├── index.html │ │ ├── terminal.css │ │ ├── terminal.dart │ │ └── terminal_filesystem.dart │ ├── geolocation/ │ │ └── trip_meter/ │ │ ├── README.md │ │ ├── index.html │ │ ├── trip_meter.css │ │ └── trip_meter.dart │ ├── indexeddb/ │ │ └── todo/ │ │ ├── README.md │ │ ├── index.html │ │ ├── todo.css │ │ └── todo.dart │ ├── localstorage/ │ │ └── basics/ │ │ ├── README.md │ │ ├── index.html │ │ └── localstorage.dart │ ├── pointerlock/ │ │ └── fps/ │ │ ├── fps.css │ │ ├── fps.dart │ │ ├── fps_camera.dart │ │ ├── fps_controller.dart │ │ ├── index.html │ │ ├── opengl.dart │ │ └── quat.dart │ ├── speed/ │ │ └── animations/ │ │ ├── README.md │ │ ├── animations.css │ │ ├── animations.dart │ │ └── index.html │ ├── video/ │ │ └── basics/ │ │ ├── README.md │ │ ├── index.html │ │ └── video.dart │ ├── webaudio/ │ │ └── intro/ │ │ ├── README.md │ │ ├── filter_sample.dart │ │ ├── index.html │ │ └── sounds/ │ │ └── example.ogg │ ├── webgl/ │ │ ├── 2d_image/ │ │ │ ├── 2d_image.dart │ │ │ └── index.html │ │ ├── 2d_image_3x3_convolution/ │ │ │ ├── 2d_image_3x3_convolution.dart │ │ │ └── index.html │ │ ├── 2d_image_blend/ │ │ │ ├── 2d_image_blend.dart │ │ │ └── index.html │ │ ├── 2d_image_processing/ │ │ │ ├── 2d_image_processing.dart │ │ │ └── index.html │ │ ├── 2d_image_red_2_blue/ │ │ │ ├── 2d_image_red_2_blue.dart │ │ │ └── index.html │ │ ├── fundamentals/ │ │ │ ├── fundamentals.dart │ │ │ └── index.html │ │ ├── rectangle/ │ │ │ ├── index.html │ │ │ └── rectangle.dart │ │ ├── rectangle_top_left/ │ │ │ ├── index.html │ │ │ └── rectangle_top_left.dart │ │ ├── rectangles/ │ │ │ ├── index.html │ │ │ └── rectangles.dart │ │ ├── resources/ │ │ │ └── webgl-tutorials.css │ │ ├── solar3d/ │ │ │ ├── README.md │ │ │ ├── pubspec.yaml │ │ │ └── web/ │ │ │ ├── camera.dart │ │ │ ├── grid.dart │ │ │ ├── orbit_path.dart │ │ │ ├── planet_shader.dart │ │ │ ├── shader.dart │ │ │ ├── skybox.dart │ │ │ ├── solar.css │ │ │ ├── solar.dart │ │ │ ├── solar.html │ │ │ ├── sphere_controller.dart │ │ │ ├── sphere_model.dart │ │ │ ├── sphere_model_data.dart │ │ │ └── texture_manager.dart │ │ └── utils/ │ │ └── webgl_utils.dart │ └── websockets/ │ └── basics/ │ ├── README.md │ ├── index.html │ └── websocket_sample.dart └── polymer_mini_samples/ ├── README.md ├── pubspec.yaml └── web/ ├── binding_data/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html ├── binding_to_a_style_value/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html ├── binding_with_built_in_elements/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html ├── creating_an_element/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html ├── creating_an_element_using_noscript/ │ ├── README.md │ ├── index.html │ └── my_element.html ├── finding_shadow_dom_nodes_by_id/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html ├── publishing_properties/ │ ├── README.md │ ├── index.html │ ├── my_element.dart │ └── my_element.html └── waiting_until_an_element_is_ready/ ├── README.md ├── index.html ├── my_element.dart └── my_element.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ # JetBrains .idea/ # Dart Editor *.dart.js *.dart.js.map *.dart.js.deps # pub .pub packages .packages build #other .settings .buildlog .DS_Store ================================================ FILE: LICENSE ================================================ Copyright 2012, the Dart project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ====================================================================== Portions of these code samples were derived from tutorials or samples on http://www.html5rocks.com. These portions are licensed as follows: Copyright 2012 - 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. ================================================ FILE: README.md ================================================ # DEPRECATED This repo is deprecated; please use the new samples repo: https://github.com/dart-lang/samples ## Contents * [HTML5 samples](html5/README.md) * [Dart I/O mini samples](dart_io_mini_samples/README.md) * [Dart deferred loading samples](deferred_loading_samples/README.md) Note: The Angulardart examples have been moved to [https://github.com/shailen/angulardart-samples](https://github.com/shailen/angulardart-samples). ================================================ FILE: dart_io_mini_samples/AUTHORS ================================================ Mary Campione Patrice Chalin Shailen Tuli Günter Zöchbauer ================================================ FILE: dart_io_mini_samples/LICENSE ================================================ Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License [1], and code samples are licensed under the BSD License: Copyright 2012, the Dart project authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [1] http://creativecommons.org/licenses/by-nc-nd/3.0/us/ ================================================ FILE: dart_io_mini_samples/README.md ================================================ * [Introduction](example/introduction.md) ## Files, directories, and symlinks * [Deleting a file, directory, or symlink](example/files_directories_and_symlinks/deleting_a_file_directory_or_symlink.dart) * [Renaming a file, directory, or symlink](example/files_directories_and_symlinks/renaming_a_file_directory_or_symlink.dart) * [Finding the type of a filesystem object](example/files_directories_and_symlinks/finding_the_type_of_a_filesystem_object.dart) * [Getting the parent directory](example/files_directories_and_symlinks/getting_the_parent_directory.dart) * [Creating a file](example/files_directories_and_symlinks/files/creating_a_file.dart) * [Reading a file as a string](example/files_directories_and_symlinks/files/reading_a_file_as_a_string.dart) * [Reading a file as lines](example/files_directories_and_symlinks/files/reading_a_file_as_lines.dart) * [Reading a file as bytes](example/files_directories_and_symlinks/files/reading_a_file_as_bytes.dart) * [Handling errors when reading a file](example/files_directories_and_symlinks/files/handling_errors_when_reading_a_file.dart) * [Writing a string to a file](example/files_directories_and_symlinks/files/writing_a_string_to_a_file.dart) * [Writing bytes to a file](example/files_directories_and_symlinks/files/writing_bytes_to_a_file.dart) * [Using a stream to write to a file](example/files_directories_and_symlinks/files/writing_to_a_file_using_a_stream.dart) * [Creating a directory](example/files_directories_and_symlinks/directories/creating_a_directory.dart) * [Creating a temp directory](example/files_directories_and_symlinks/directories/creating_a_temporary_directory.dart) * [Listing the contents of a directory](example/files_directories_and_symlinks/directories/listing_the_contents_of_a_directory.dart) * [Creating a symlink](example/files_directories_and_symlinks/symlinks/creating_a_symlink.dart) * [Checking if a path represents a symlink](example/files_directories_and_symlinks/symlinks/checking_if_a_path_represents_a_symlink.dart) * [Getting the target of a symlink](example/files_directories_and_symlinks/symlinks/getting_the_target_of_a_link.dart) ## HTTP requests and responses * [Making a GET request](example/http/making_a_get_request.dart) * [Making a POST request](example/http/making_a_post_request.dart) * [Adding custom headers to a request](example/http/adding_custom_headers.dart) * [Making multiple requests to the same server](example/http/making_multiple_requests_to_the_same_server.dart) * [Handling errors when making a request](example/http/handling_an_httprequest_error.dart) * [Getting redirection history](example/http/getting_redirection_history.dart) * [Getting the response body as a string](example/http/reading_the_response_body.dart) * [Getting the response content in binary format](example/http/getting_the_response_content_in_binary_format.dart) * [Getting the response headers](example/http/getting_the_response_headers.dart) ## HTTP server * [Implementing a 'Hello world' HTTP server](example/http_server/implementing_a_Hello_World_http_server.dart) * [Routing requests based on URL patterns](example/http_server/routing_requests_based_on_url_patterns.dart) ## Sockets * [Using serversockets server](example/sockets/using_serversockets_server.dart) * [Using serversockets client](example/sockets/using_serversockets_client.dart) ## Websockets * [Using websockets server](example/websockets/using_websockets_server.dart) * [Using websockets client](example/websockets/using_websockets_client.dart) ## OS and hardware information * [Getting environment variables](example/platform/getting_environment_variables.dart) * [Identifying the operating system](example/platform/identifying_the_operating_system.dart) * [Getting information about the script being run](example/platform/getting_information_about_the_script_being_run.dart) ## Interacting with processes * [Running a process](example/interacting_with_processes/running_a_process.dart) * [Obtaining the exit code when running a process](example/interacting_with_processes/obtaining_the_exit_code_when_running_a_process.dart) ## Working with paths * [Joining paths](example/paths/joining_paths.dart) * [Parsing a path into components](example/paths/parsing_a_path_into_components.dart) * [Calculating relative paths](example/paths/calculating_relative_paths.dart) * [Converting between a URI and a path](example/paths/converting_between_a_uri_and_a_path.dart) * [Getting information about a file path](example/paths/getting_information_about_a_file_path.dart) * [Getting the path separator for the current platform](example/paths/getting_the_path_separator_for_the_current_platform.dart) ## Other resources * [Other resources](example/other_resources.md) ================================================ FILE: dart_io_mini_samples/example/common.css ================================================ body { padding-right: 15px; padding-left: 15px; margin: 20px auto 0 auto; font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 14px; line-height: 1.428571429; color: #333; background-color: #fff; } input[type="text"], textarea { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.428571429; color: #555; vertical-align: middle; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; font-family: inherit; font-size: inherit; line-height: inherit; } input[type="checkbox"] { float: left; margin-left: -20px; margin: 3px 5px 0 0; margin-top: 1px \9; line-height: normal; padding: 0; box-sizing: border-box; } label { display: inline; margin-bottom: 0; font-weight: normal; cursor: pointer; } select { display: block; width: 100%; height: 34px; padding: 6px 12px; font-size: 14px; line-height: 1.428571429; color: #555; vertical-align: middle; background-color: #fff; background-image: none; border: 1px solid #ccc; border-radius: 4px; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; } button, input[type='submit'] { display: inline-block; padding: 6px 12px; margin-top: 10px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.428571429; text-align: center; white-space: nowrap; vertical-align: middle; cursor: pointer; background-image: none; border: 1px solid transparent; border-radius: 4px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; color: #fff; background-color: #428bca; border-color: #357ebd; } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/deleting_a_file_directory_or_symlink.dart ================================================ // Copyright (c) 2013, 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. /// Use the FilesSystemEntity `delete()` method to delete a file, directory, or /// symlink. This method is inherited by File, Directory, and Link. import 'dart:io'; main() async { // Create a temporary directory. var dir = await Directory.systemTemp.createTemp('my_temp_dir'); // Confirm it exists. print(await dir.exists()); // Delete the directory. await dir.delete(); // Confirm it no longer exists. print(await dir.exists()); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/directories/creating_a_directory.dart ================================================ // Copyright (c) 2013, 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. /// Use the Directory `create()` method to create a directory. /// To create intermediate directories, set the `recursive` argument to `true` /// (default is `false`). import 'dart:io'; main() async { // Creates dir/ and dir/subdir/. var directory = await new Directory('dir/subdir').create(recursive: true); print(directory.path); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/directories/creating_a_temporary_directory.dart ================================================ // Copyright (c) 2013, 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. /// Use the Directory `createTemp()` method to create a temporary directory. /// This method appends random characters to the name of the directory to /// produce a unique directory name. import 'dart:io'; main() async { var directory = await Directory.systemTemp.createTemp('my_temp_dir'); print(directory.path); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/directories/listing_the_contents_of_a_directory.dart ================================================ // Copyright (c) 2013, 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. /// Use the `list()` method to list a directory's contents. The method recurses /// into subdirectories if the `recursive` argument is `true` (default is /// `false`). It does not follow symlinks if the `followLinks` argument is /// `false` (default is `true`). import 'dart:io'; import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. main() async { // Get the system temp directory. var systemTempDir = Directory.systemTemp; // List directory contents, recursing into sub-directories, but not following // symbolic links. Stream entityList = systemTempDir.list(recursive: true, followLinks: false); await for (FileSystemEntity entity in entityList) print(entity.path); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/file.txt ================================================ one banana two banana three banana four ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/creating_a_file.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `create()` method to create a file. /// To create intermediate directories, set the `recursive` argument to /// `true` (default is `false`). import 'dart:io'; main() async { // Get the system temp directory. var systemTempDir = Directory.systemTemp; // Creates dir/, dir/subdir/, and dir/subdir/file.txt in the system // temp directory. var file = await new File('${systemTempDir.path}/dir/subdir/file.txt') .create(recursive: true); print(file.path); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/handling_errors_when_reading_a_file.dart ================================================ // Copyright (c) 2013, 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. import 'dart:io'; main() async { final filename = 'non_existent_file.txt'; try { var file = await new File(filename).readAsString(); print(file); } catch (e) { print('There was a ${e.runtimeType} error'); print('Could not read $filename'); } } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_a_string.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `readAsString()` method to read a file as a string. import 'dart:io'; main() async { var contents = await new File('file.txt').readAsString(); print(contents); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_bytes.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `readAsBytes()` method to read file contents as bytes. import 'dart:io'; import 'package:crypto/crypto.dart'; main() async { var bytes = await new File('file.txt').readAsBytes(); // Do something with the bytes. For example, convert to base64. String base64 = CryptoUtils.bytesToBase64(bytes); print(base64); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_lines.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `readAsLines()` method to read file contents as lines. import 'dart:io'; main() async { List lines = await new File('file.txt').readAsLines(); lines.forEach((String line) => print(line)); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_using_a_stream.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `openRead()` method to read a file's contents a little at a /// time using a stream. /// /// The example below reads the file fragments, decodes them to UTF8, and /// converts them to individual lines. The `onDone` callback executes when the /// stream exhausts. The `onError` callback executes when there is an error. import 'dart:io'; import 'dart:convert'; import 'dart:async'; main() async { final file = new File('file.txt'); Stream> inputStream = file.openRead(); Stream lines = inputStream // Decode to UTF8. .transform(UTF8.decoder) // Convert stream to individual lines. .transform(new LineSplitter()); try { await for (String line in lines) print('$line: ${line.length} bytes'); } catch (e) { print(e.toString()); } print('File is now closed.'); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_a_string_to_a_file.dart ================================================ // Copyright (c) 2013, 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. /// Use the File object's `writeAsString()` method to write a string to a /// file. After writing the string, the method closes the file. import 'dart:io'; main() async { final filename = 'file.txt'; var file = await new File(filename).writeAsString('some content'); print("Content written to $file"); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_bytes_to_a_file.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `writeAsBytes()` method to write bytes to a file. import 'dart:io'; import 'dart:convert'; main() async { final string = 'Dart!'; // Encode to UTF8. var encodedData = UTF8.encode(string); var file = await new File('file.txt'); file.writeAsBytes(encodedData); var data = await file.readAsBytes(); // Decode to a string, and print. print(UTF8.decode(data)); // Prints 'Dart!'. } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_to_a_file_using_a_stream.dart ================================================ // Copyright (c) 2013, 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. /// Use the File `openWrite()` method to create a new IOSink for a file, to /// write to the file a little at a time. /// To append to the file, set the `mode` argument to `FileMode.APPEND` /// (it defaults to `FileMode.WRITE`). import 'dart:io'; main() { var file = new File('file.txt'); var sink = file.openWrite(); sink.write('FILE ACCESSED ${new DateTime.now()}\n'); // Close the IOSink to free system resources. sink.close(); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/finding_the_type_of_a_filesystem_object.dart ================================================ // Copyright (c) 2013, 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. /// Use the `FileSystemEntity.type()` method to get the type of a file system /// object. This method is inherited by File, Directory, and Link. import 'dart:io'; import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. main() async { // List the contents of the system temp directory. Stream entityList = Directory.systemTemp.list(recursive: true, followLinks: false); await for (FileSystemEntity entity in entityList) { // Get the type of the FileSystemEntity, apply the appropiate label, and // print the entity path. FileSystemEntityType type = await FileSystemEntity.type(entity.path); String label; switch (type) { case FileSystemEntityType.DIRECTORY: label = 'D'; break; case FileSystemEntityType.FILE: label = 'F'; break; case FileSystemEntityType.LINK: label = 'L'; break; default: label = 'UNKNOWN'; } print('$label: ${entity.path}'); } } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/getting_the_parent_directory.dart ================================================ // Copyright (c) 2013, 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. /// Use the FileSystemEntity `parent` property to get the parent of a /// file, directory, or symlink. This property is inherited by File, Directory, /// and Link. import 'dart:io'; import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. main() async { // List the contents of the system temp directory. Stream entityList = Directory.systemTemp.list(recursive: true, followLinks: false); await for (FileSystemEntity entity in entityList) print(entity.parent.path); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/renaming_a_file_directory_or_symlink.dart ================================================ // Copyright (c) 2013, 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. /// Use the FileSystemEntity `rename()` method to change the name of a /// file, directory or symlink. This method is inherited by /// File, Directory, and Link. import 'dart:io'; main() async { // Get the system temp directory. var systemTempDir = Directory.systemTemp; // Create a file. var file = await new File('${systemTempDir.path}/foo.txt').create(); // Prints path ending with `foo.txt`. print('The path is ${file.path}'); // Rename the file. await file.rename('${systemTempDir.path}/bar.txt'); // Prints path ending with `bar.txt`. print('The path is ${file.path}'); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/checking_if_a_path_represents_a_symlink.dart ================================================ /// Use the FileSystemEntity `isLink()` method to check if path represents /// a symlink. import 'dart:io'; import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. main() async { // Get the system temp directory. var systemTempDir = Directory.systemTemp; // List the contents of the system temp directory. Stream entityList = systemTempDir.list(recursive: true, followLinks: false); await for (FileSystemEntity entity in entityList) { // Print the path only if it represents a symlink. var isLink = await FileSystemEntity.isLink(entity.path); if (isLink) print(entity.path); } } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/creating_a_symlink.dart ================================================ /// Use the Link `create()` method to create a symlink. import 'dart:io'; main() async { // Get the system temp directory. var temp = await Directory.systemTemp.createTemp('my_temp_dir'); // Generate a couple of paths. var first = '${temp.path}${Platform.pathSeparator}first'; var second = '${temp.path}${Platform.pathSeparator}second'; // Create a symlink. Link symLink = await new Link(second).create(first); print(symLink); } ================================================ FILE: dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/getting_the_target_of_a_link.dart ================================================ /// Use the Link `target()` method to get the path that the link points to. import 'dart:async'; import 'dart:io'; // Creates temporary directory inside the system temp directory, creates a // couple of paths in the created directory, and creates a symlink. Future createSymLink() async { var temp = await Directory.systemTemp.createTemp('my_temp_dir'); var first = '${temp.path}${Platform.pathSeparator}first'; var second = '${temp.path}${Platform.pathSeparator}second'; return new Link(second).create(first); } main() async { try { var link = await createSymLink(); print(link.path); var targetPath = await link.target(); print(targetPath); } catch (e) { print(e.message); } } ================================================ FILE: dart_io_mini_samples/example/http/adding_custom_headers.dart ================================================ // Copyright (c) 2013, 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. /// Use the `headers` argument to the function used to make an HTTP request. /// The example below adds a 'User-Agent' header to a `get` request. import 'dart:convert'; import 'package:http/http.dart' as http; main() async { var url = 'https://api.github.com/users/dart-lang/repos'; var response = await http.get(url, headers: {'User-Agent': 'Dart/1.0 (My Dart client)'}); List repos = JSON.decode(response.body); var heading = 'Repository | Star count | Fork count'; print(heading); print(new List.filled(heading.length, '=').join()); for (var repo in repos) { print("${repo['name']} | " "${repo['stargazers_count']} | " "${repo['forks_count']}"); } } ================================================ FILE: dart_io_mini_samples/example/http/getting_redirection_history.dart ================================================ // Copyright (c) 2013, 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. /// Use the `HttpClient` class in the 'dart:io' library to make a request, and /// use the Response `redirects` property to get a list of the redirects. import "dart:io" show HttpClient, RedirectInfo; main() async { var client = new HttpClient(); var request = await client.getUrl(Uri.parse('http://google.com')); var response = await request.close(); List redirects = response.redirects; redirects.forEach((redirect) { print(redirect.location); // Prints 'http://www.google.com'. }); } ================================================ FILE: dart_io_mini_samples/example/http/getting_the_response_content_in_binary_format.dart ================================================ // Copyright (c) 2013, 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. /// Use the `bodyBytes` field on the Response object to get the response /// in bytes. import 'package:http/http.dart' as http; import 'package:crypto/crypto.dart'; main() async { var url = "https://www.dartlang.org/logos/dart-logo.png"; var response = await http.get(url); List bytes = response.bodyBytes; // Do something with the bytes. For example, convert to base64. String base64 = CryptoUtils.bytesToBase64(bytes); print(base64); } ================================================ FILE: dart_io_mini_samples/example/http/getting_the_response_headers.dart ================================================ // Copyright (c) 2013, 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. /// Use the `headers` field of the Response object to get a headers Map. /// The map keys are the header fields, and the map values are the values of /// those fields. import 'package:http/http.dart' as http; main() async { var url = 'http://httpbin.org/'; var response = await http.get(url); // Get the headers map. print(response.headers.keys); // Get header values. print( "access-control-allow-origin' = ${response.headers['access-control-allow-origin']}"); print("content-type = ${response.headers['content-type']}"); print("date = ${response.headers['date']}"); print("content-length = ${response.headers['content-length']}"); print("connection = ${response.headers['connection']}"); } ================================================ FILE: dart_io_mini_samples/example/http/handling_an_httprequest_error.dart ================================================ // Copyright (c) 2013, 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. /// An HTTP request may return a response, or it may generate an error. import 'package:http/http.dart' as http; handleSuccess(http.Response response) { print('something went right!'); print(response.body); } handleFailure(error) { print('Something went wrong.'); print(error.message); } main() async { try { var response = await http.get("http://some_bogus_website.org"); handleSuccess(response); } catch (e) { handleFailure(e); } } ================================================ FILE: dart_io_mini_samples/example/http/making_a_get_request.dart ================================================ // Copyright (c) 2013, 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. /// Use the http package `get()` function to make a GET request. import 'package:http/http.dart' as http; main() async { var url = 'http://httpbin.org/'; var response = await http.get(url); print("Response status: ${response.statusCode}"); print("Response body: ${response.body}"); } ================================================ FILE: dart_io_mini_samples/example/http/making_a_post_request.dart ================================================ // Copyright (c) 2013, 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. /// Use the http package `post()` function to make a POST request. import 'package:http/http.dart' as http; main() async { var url = 'http://httpbin.org/post'; var response = await http.post(url, body: 'name=doodle&color=blue'); print("Response status: ${response.statusCode}"); print("Response body: ${response.body}"); } ================================================ FILE: dart_io_mini_samples/example/http/making_multiple_requests_to_the_same_server.dart ================================================ // Copyright (c) 2013, 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. /// Use the `Client` class in the http Pub package for making multiple requests /// to the same server. Using `Client` keeps keep a persistent connection open /// to the server and is better than making multiple single requests. import 'package:http/http.dart' as http; printResponseBody(response) { print(response.body.length); if (response.body.length > 100) { print(response.body.substring(0, 100)); } else { print(response.body); } print('...\n'); } main() async { var url = 'http://www.google.com/'; var client = new http.Client(); try { var response = await client.get('$url/search'); printResponseBody(response); response = await client.get('$url/doodles'); printResponseBody(response); } finally { client.close(); } } ================================================ FILE: dart_io_mini_samples/example/http/reading_the_response_body.dart ================================================ // Copyright (c) 2013, 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. /// Read the response body using the `read()` function defined in the http Pub /// package. import 'package:http/http.dart' as http; main() async { print(await http.read("http://www.google.com/")); } ================================================ FILE: dart_io_mini_samples/example/http_server/implementing_a_Hello_World_http_server.dart ================================================ // Copyright (c) 2013-2014, 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. /// Use `HttpServer.bind()` method to bind to a port. /// The await for listens for connections. /// Respond to an `HttpRequest` using the `response` property. import 'dart:io'; main() async { var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080); print("Serving at ${server.address}:${server.port}"); await for (HttpRequest request in server) { request.response ..headers.contentType = new ContentType("text", "plain", charset: "utf-8") ..write('Hello, world') ..close(); } } ================================================ FILE: dart_io_mini_samples/example/http_server/routing_requests_based_on_url_patterns.dart ================================================ // Copyright (c) 2013-2014, 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. /// Use the `route` Pub package, and associate callbacks with URL patterns. import 'dart:io'; import 'package:route/server.dart'; import 'package:route/url_pattern.dart'; // Pattern for all posts (plural). final postsUrl = new UrlPattern(r'/posts\/?'); // Pattern for a single post('/post/24', for example). final postUrl = new UrlPattern(r'/post/(\d+)\/?'); // Callback for all posts (plural). servePosts(req) { req.response.write("All blog posts"); req.response.close(); } // Callback for a single post('/post/24', for example). servePost(req) { var postId = postUrl.parse(req.uri.path)[0]; req.response.write('Blog post $postId'); req.response.close(); } // Callback to handle illegal urls. serveNotFound(req) { req.response.statusCode = HttpStatus.NOT_FOUND; req.response.write('Not found'); req.response.close(); } main() async { var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080); var router = new Router(server) // Associate callbacks with URLs. ..serve(postsUrl, method: 'GET').listen(servePosts) ..serve(postUrl, method: 'GET').listen(servePost) ..defaultStream.listen(serveNotFound); } ================================================ FILE: dart_io_mini_samples/example/http_server/web/foo.html ================================================

This is foo.html

================================================ FILE: dart_io_mini_samples/example/http_server/web/index.html ================================================

This is index.html

================================================ FILE: dart_io_mini_samples/example/interacting_with_processes/obtaining_the_exit_code_when_running_a_process.dart ================================================ // Copyright (c) 2013, 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. /// Use `Process.start()` to start a process to run an executable. This function /// returns a new process that you can use to interact with the original /// process. You can use this returned process to obtain the exit code from /// executing the original process. import 'dart:io'; main() async { var process = await Process.start('ls', ['-l']); // Get the exit code from the new process. var exitCode = await process.exitCode; print('exit code: $exitCode'); } ================================================ FILE: dart_io_mini_samples/example/interacting_with_processes/running_a_process.dart ================================================ // Copyright (c) 2013, 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. /// Use `Process.run()` to run a process. The results of the process are /// returned asynchronously using a ProcessResult object. import 'dart:io'; main() async { // List all files in the current directory in UNIX-like operating systems. var results = await Process.run('ls', ['-l']); print(results.stdout); } ================================================ FILE: dart_io_mini_samples/example/introduction.md ================================================ The following examples are all stand-alone apps, such as servers, that run from the command line. Most of the examples use the `dart:io` library, which is used solely for command-line applications running on a stand-alone Dart VM. The `dart:io` library does not work in browser-based applications. Many examples also use Pub packages. See the [source on Github](https://github.com/dart-lang/dart-samples/tree/master/dart_io_mini_samples). After looking at the following code examples, refer to [Write Command-line Apps](/tutorials/dart-vm/cmdline) for additional information about I/O and command-line apps. ================================================ FILE: dart_io_mini_samples/example/other_resources.md ================================================ Read the [dart:io library API docs]({{site.dart_api}}/dart-io/dart-io-library.html). Here are links to the commonly used classes and packages in these examples: * Using files, directories, and symlinks * [FileSystemEntity class]({{site.dart_api}}/dart-io/FileSystemEntity-class.html) * [File class]({{site.dart_api}}/dart-io/File-class.html) * [Directory class]({{site.dart_api}}/dart-io/Directory-class.html) * [Link class (for symlinks)]({{site.dart_api}}/dart-io/Link-class.html) * HTTP server * [HttpServer class]({{site.dart_api}}/dart-io/HttpServer-class.html) * [http_server Pub package](https://pub.dartlang.org/packages/http_server) * OS and hardware information * [Platform class]({{site.dart_api}}/dart-io/Platform-class.html) * Interacting with processes * [Process class]({{site.dart_api}}/dart-io/Process-class.html) * Working with paths * [path Pub package](https://pub.dartlang.org/packages/path) ================================================ FILE: dart_io_mini_samples/example/paths/calculating_relative_paths.dart ================================================ // Copyright (c) 2013, 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. /// Use the `relative()` function in the `path` Pub package to calculate /// relative paths. This function calculates the relative path from the current /// directory by default. To calculate the relative path from another path, /// specify that path using the `from` argument. import 'dart:io' show Directory; import 'package:path/path.dart' as path; main() { // The path from the current directory to the system temp directory. print(path.relative(Directory.systemTemp.path)); // You can work with relative paths. var path1 = 'docs/book.html'; var path2 = 'articles/list'; print(path.relative(path1, from: path2)); // Prints '../../docs/book.html'. print(path.relative(path2, from: path1)); // Prints '../../articles/list'. // Or you can work with absolute paths. var samples = 'http://www.dartlang.org/samples'; var docs = 'http://www.dartlang.org/docs'; print(path.relative(samples, from: docs)); // Prints '../samples'. } ================================================ FILE: dart_io_mini_samples/example/paths/converting_between_a_uri_and_a_path.dart ================================================ // Copyright (c) 2013, 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. /// Use the `toUri()` and `fromUri()` functions in the `path` Pub package when /// converting between a URI and a path. import 'package:path/path.dart' as path; main() { var uri = path.toUri('http://dartlang.org/samples'); print(path.fromUri(uri)); // Prints 'http:/dartlang.org/samples'. } ================================================ FILE: dart_io_mini_samples/example/paths/getting_information_about_a_file_path.dart ================================================ // Copyright (c) 2013, 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. /// Use the `basename()`, `dirname()`, `basenameWithoutExtension()`, and /// `extension()` methods defined in the `path` Pub package when working with /// a file path. import 'package:path/path.dart' as path; import 'dart:io'; main() async { // Create dir/ and dir/file.txt in the system temp directory. var file = await new File('${Directory.systemTemp.path}/dir/myFile.txt') .create(recursive: true); print(path.basename(file.path)); // Prints 'file.txt'. print(path.dirname(file.path)); // Prints path ending with 'dir'. print(path.basenameWithoutExtension(file.path)); // Prints 'myFile'. print(path.extension(file.path)); // Prints '.txt'. } ================================================ FILE: dart_io_mini_samples/example/paths/getting_the_path_separator_for_the_current_platform.dart ================================================ // Copyright (c) 2013, 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. /// Use `Platform.pathSeparator` to get the separator used by the operating /// system to separate components in file. Or, use the `separator` getter /// in the `path` Pub package. import 'dart:io' show Platform; import 'package:path/path.dart' as path; main() { // Prints '\' on Windows and '/' on other platforms. print(Platform.pathSeparator); // This does the same. print(path.separator); } ================================================ FILE: dart_io_mini_samples/example/paths/joining_paths.dart ================================================ // Copyright (c) 2013, 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. /// Use the path Pub package, and use `join()` to create a new path from /// existing paths. Using `join()` ensures that the current platform's directory /// separator is used in the path. import 'package:path/path.dart' as path; main() { var newPath = path.join('/Users/shailen', 'dart/projects'); print(newPath); // Prints '/Users.shailen/dart/projects'. } ================================================ FILE: dart_io_mini_samples/example/paths/parsing_a_path_into_components.dart ================================================ // Copyright (c) 2013, 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. /// Use the `split()` function in the `path` Pub package to split a path into /// its components. import 'package:path/path.dart' as path; main() { print(path.split('/Users/shailen')); // Prints ['/', 'Users', 'shailen']. // Windows example. print(path .split(r'C:\tempdir\tmp.txt')); // Prints [r'C:\', 'tempdir', 'tmp.txt']) } ================================================ FILE: dart_io_mini_samples/example/platform/getting_environment_variables.dart ================================================ // Copyright (c) 2013, 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. /// Use `Platform.environment` to get the environment for the current process. import 'dart:io' show Platform; main() { Map envVars = Platform.environment; print(envVars['PATH']); } ================================================ FILE: dart_io_mini_samples/example/platform/getting_information_about_the_script_being_run.dart ================================================ // Copyright (c) 2013, 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. /// Use `Platform.script` to get the absolute URI of the script being run in /// the current isolate. import 'dart:io' show Platform; main() { // Get the URI of the script being run. var uri = Platform.script; print(uri); // Prints something like '/Users/shailentuli/workspace/...'. // Convert the URI to a path. var path = uri.toFilePath(); print( path); // Prints something like 'file:///Users/shailentuli/workspace/...'. } ================================================ FILE: dart_io_mini_samples/example/platform/identifying_the_operating_system.dart ================================================ // Copyright (c) 2013, 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. /// Use `Platform.operatingSystem` to get the operating system as a String. /// Or, use the `isMacOS`, `isAndroid`, `isLinux`, and `isWindows` static /// getters defined in `Platform`. import 'dart:io' show Platform, stdout; main() { // Get the operating system as a string. String os = Platform.operatingSystem; // Or, use predicate getters for checking the operating system. stdout.write("You are using "); if (Platform.isMacOS) { stdout.writeln('a Mac'); } else if (Platform.isAndroid) { stdout.writeln('an Android device'); } else if (Platform.isIOS) { stdout.writeln('an iOS device'); } else if (Platform.isLinux) { stdout.writeln('Linux'); } else if (Platform.isWindows) { stdout.writeln('Windows'); } else { stdout.writeln('something other than MacOS, Android, Linux, or Windows'); } } ================================================ FILE: dart_io_mini_samples/example/sockets/using_serversockets_client.dart ================================================ // Copyright (c) 2013, 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. /// Create a new socket connection using `Socket.connect()`. Send data over the /// socket using the Socket `write()` method. /// import 'dart:io'; main() async { var socket = await Socket.connect('127.0.0.1', 4041); print(socket.runtimeType); socket.write('Hello, World!'); } ================================================ FILE: dart_io_mini_samples/example/sockets/using_serversockets_server.dart ================================================ // Copyright (c) 2013, 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. /// Use `ServerSocket.bind()` to bind to an address and a port. Get the socket /// from the ServerSocket and listen to it for the data. import 'dart:io'; import 'dart:convert'; main() async { var serverSocket = await ServerSocket.bind('127.0.0.1', 4041); print('connected'); await for (var socket in serverSocket) socket.transform(UTF8.decoder).listen(print); } ================================================ FILE: dart_io_mini_samples/example/websockets/using_websockets_client.dart ================================================ // Copyright (c) 2013, 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. /// Make a WebSocket connection using `WebSocket.connect()`, and send data /// over that connection using the WebSocket `add()` method. import 'dart:io'; main() async { var socket = await WebSocket.connect('ws://127.0.0.1:4040/ws'); socket.add('Hello, World!'); } ================================================ FILE: dart_io_mini_samples/example/websockets/using_websockets_server.dart ================================================ // Copyright (c) 2013, 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. /// Upgrade a regular HTTP request to a WebSocket request using /// `WebSocketTransformer.upgrade()`. import 'dart:io'; handleMsg(msg) { print('Message received: $msg'); } main() async { try { var server = await HttpServer.bind('127.0.0.1', 4040); await for (HttpRequest req in server) { if (req.uri.path == '/ws') { // Upgrade an HttpRequest to a WebSocket connection. var socket = await WebSocketTransformer.upgrade(req); socket.listen(handleMsg); } } } catch (e) { print(e); } } ================================================ FILE: dart_io_mini_samples/generate_md_for_dartlang.dart ================================================ // // Run "dart generate_md_for_dartlang.dart > index.md". // Copy that file to /dart-vm/dart-by-example in the www repo. // This file uses fodder from README.md and example/* to generate // the final page. // import 'dart:io'; import 'package:path/path.dart' as PATH; // text.gsub /\[([^\]]+)\]\(([^)]+)\)/, '\1' printExample(List lines) { var i = 0; for (; i < lines.length; i++) { var line = lines[i].trim(); // Get the first non-empty, non-comment line. if (line.startsWith('//') || (line.isEmpty)) { if (line.startsWith('/// ')) { print(line.substring(3).trim()); } } else { break; } } print(''); print('{% prettify dart %}'); print(lines.getRange(i, lines.length).join('\n')); print('{% endprettify %}'); print(''); } const fileHeader = ''' --- layout: default title: "Cookbook: Dart by Example" short-title: "Cookbook" permalink: /dart-vm/dart-by-example description: "A cookbook, or set of examples, showing idiomatic Dart code." header: css: ["index.css"] --- '''; main() { print(fileHeader); // RegExp to match a markdown link such as [Google](http://google.com) var regExp = new RegExp(r'\[([^\]]+)\]\(([^)]+)\)'); var readme = new File('README.md').readAsLinesSync(); for (var line in readme) { line = line.trim(); if (line.startsWith("*")) { if (regExp.hasMatch(line)) { var match = regExp.firstMatch(line); print(''); var abspath = PATH.absolute(match.group(2)); var file = new File(abspath); if (PATH.extension(abspath) != '.md') { print('### ${match.group(1)}'); print(''); printExample(file.readAsLinesSync()); } else { print(file.readAsStringSync()); } } } else { // Print non-link lines from the README. print(line); } } } ================================================ FILE: dart_io_mini_samples/pubspec.yaml ================================================ name: dart_by_example description: Examples that teach the use of Dart through short, directed code snippets. dependencies: crypto: any http: any http_server: any path: any route: any ================================================ FILE: dart_io_mini_samples/runtests.sh ================================================ #!/bin/bash # #------------------------------------------------------------------------------ function usage() { cat <<'EOM' Usage: runtests.sh [-q|+h|-h] -h print this usage message. +h report all hints as problems; otherwise only unused imports are counted as problems. -q quiet mode (only emit output if the analyzer finds problems). Verbose by default. EOM } #------------------------------------------------------------------------------ declare -i problem_count EXIT_STATUS=0 PASSING=0 FAILURES=0 VERBOSE=1; BASE_DIR=$(dirname $0) while [ $# -gt 0 ]; do case $1 in -h) usage; exit 0;; +h) count_all_hints_as_problems=1; shift;; -q) VERBOSE=; shift;; -*) echo "Invalid option: $1"; usage; exit 1;; esac done [[ -n "$VERBOSE" ]] && echo "Running dartanalyzer on *.dart files in $BASE_DIR" for file in `find $BASE_DIR -name "*.dart"` do [[ -n "$VERBOSE" ]] && echo $file results=$(dartanalyzer $file 2>&1) problem_count=$(echo "$results" | grep -E "^\[(error|warning)\]" | wc -l) if [[ -n "$count_all_hints_as_problems" ]]; then problem_count+=$(echo "$results" | grep -E "^\[hint\]" | wc -l) else # hints such as 'Unused import' should be treated as warnings. problem_count+=$(echo "$results" | grep -E "^\[hint\] Unused import" | wc -l) fi if [ "$problem_count" -gt 0 ]; then echo "$results" EXIT_STATUS=1 let FAILURES++ else let PASSING++ fi; done if [[ -n "$VERBOSE" || "$FAILURES" -gt 0 ]]; then echo "-------------------------------------------------------------------" echo "$PASSING PASSED, $FAILURES FAILED " echo "-------------------------------------------------------------------" fi exit $EXIT_STATUS ================================================ FILE: deferred_loading_samples/README.md ================================================ dart-deferred-loading-examples ============================== This directory includes deferred loading examples for the Dart language. [deferred_loading_example](deferred_loading_example/README.md) : A tiny command-line example that loads a single deferred library on startup. [lazyloader](lazyloader/README.md) : A browser-based example that loads one of three libraries when the user clicks the corresponding button. For more information, see [Dart Deferred Loading](https://www.dartlang.org/docs/spec/deferred-loading.html). ================================================ FILE: deferred_loading_samples/deferred_loading_example/README.md ================================================ This project demonstrates the simplest example of deferred loading. The lib/hello.dart file is loaded lazily, on startup. Once loaded, the library prints a Hello World style greeting. You can run this from the command line, using `pub run bin/main', for example. For more information, see [Dart Deferred Loading](/docs/spec/deferred-loading.html). ================================================ FILE: deferred_loading_samples/deferred_loading_example/bin/main.dart ================================================ import 'package:deferred_loading_example/hello.dart' deferred as hello; main() async { await hello.loadLibrary(); hello.printGreeting(); } ================================================ FILE: deferred_loading_samples/deferred_loading_example/lib/hello.dart ================================================ library deferred_loading_example.hello; printGreeting() { print('Hello World, from the deferred library!'); } ================================================ FILE: deferred_loading_samples/deferred_loading_example/pubspec.yaml ================================================ name: deferred_loading_example description: A sample web application that loads a library lazily. ================================================ FILE: deferred_loading_samples/lazyloader/README.md ================================================ This project demonstrates a very simple example of deferred loading. The breakfast.dart, lunch.dart, and dinner.dart libraries (in /lib) are loaded lazily, when the user clicks the **Breakfast menu**, **Lunch menu**, or **Dinner menu** buttons in the browser, respectively. For more information, see the language tour's [deferred loading section](https://www.dartlang.org/guides/language/language-tour#lazily-loading-a-library). ================================================ FILE: deferred_loading_samples/lazyloader/lib/breakfast.dart ================================================ library lazyloader.breakfast; const String menu = "Scrambled eggs, toast, berries, and coffee."; ================================================ FILE: deferred_loading_samples/lazyloader/lib/dinner.dart ================================================ library lazyloader.dinner; const String menu = "Lasagna, green salad, garlic bread, and red wine."; ================================================ FILE: deferred_loading_samples/lazyloader/lib/lunch.dart ================================================ library lazyloader.lunch; const String menu = "Grilled cheese sandwich, tomato soup, and juice."; ================================================ FILE: deferred_loading_samples/lazyloader/pubspec.yaml ================================================ name: lazyloader description: A sample web application dependencies: browser: any ================================================ FILE: deferred_loading_samples/lazyloader/web/index.html ================================================ Choose a Meal!

Choose a Meal!

================================================ FILE: deferred_loading_samples/lazyloader/web/main.dart ================================================ import 'dart:html'; import "package:lazyloader/breakfast.dart" deferred as breakfast; import "package:lazyloader/lunch.dart" deferred as lunch; import "package:lazyloader/dinner.dart" deferred as dinner; main() { querySelector('#show-breakfast').onClick.listen((_) async { await breakfast.loadLibrary(); onBreakfastLoaded(); }); querySelector('#show-lunch').onClick.listen((_) async { await lunch.loadLibrary(); onLunchLoaded(); }); querySelector('#show-dinner').onClick.listen((_) async { await dinner.loadLibrary(); onDinnerLoaded(); }); } onBreakfastLoaded() { print('breakfast loaded'); changeMenu(breakfast.menu); } onLunchLoaded() { print('lunch loaded'); changeMenu(lunch.menu); } onDinnerLoaded() { print('dinner loaded'); changeMenu(dinner.menu); } changeMenu(String menu) { var el = querySelector("#text_id"); el.text = menu; } ================================================ FILE: deferred_loading_samples/lazyloader/web/styles.css ================================================ body { background-color: #F8F8F8; font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: normal; line-height: 1.2em; margin: 15px; } h1, p { color: #333; } #sample_text_id { font-size: 24pt; text-align: center; margin-top: 140px; -webkit-user-select: none; user-select: none; } ================================================ FILE: html5/AUTHORS ================================================ Shannon -jj Behrens Matthew Butler Jason Brooks Richard Griffith Seth Ladd Andrei Mouravski John McCutchan Adam Singer Shailen Tuli ================================================ FILE: html5/README.md ================================================ ## Dart HTML5 Samples Most of them were ported from [HTML5 Rocks](http://www.html5rocks.com/). So far, the samples cover HTML5 topics. We want to expand the scope of the samples to cover other topics as well. * [Using Application Cache](web/appcache/beginner) * [High DPI Canvas](web/canvas/hidpi) * [Using Image Filters with Canvas](web/canvas/imagefilters) * [Basic Drag and Drop](web/dnd/basics) * [Using the File APIs](web/file/dndfiles) * [Exploring the FileSystem APIs](web/file/filesystem) * [A Terminal Emulator that uses the FileSystem APIs](web/file/terminal) * [Trip Meter: A Basic Geolocation Example](web/geolocation/trip_meter) * [Simple Todo App using IndexedDB](web/indexeddb/todo) * [LocalStorage 101](web/localstorage/basics) * [Pointer Lock And First Person Shooter Controls](web/pointerlock/fps) * [Working with RequestAnimationFrame](web/speed/animations) * [HTML5 Video](web/video/basics) * [Getting Started with the Web Audio API](web/webaudio/intro) * [3D Solar System Simulation](web/webgl/solar3d) * [WebSockets 101](web/websockets/basics) ================================================ FILE: html5/pubspec.yaml ================================================ name: dart_samples version: 0.0.1-dev description: Samples for Dart homepage: https://github.com/dart-lang/dart-samples environment: sdk: '>=0.6.17' dependencies: browser: any vector_math: any hop: any path: any html5lib: any ================================================ FILE: html5/tool/hop_runner.dart ================================================ library hop_runner; import 'dart:io'; import 'package:path/path.dart' as path; import 'package:hop/hop.dart'; import 'package:hop/hop_tasks.dart'; import 'package:html5lib/parser.dart' show parse; Iterable getHtmlPaths() { return new Directory('web').listSync(recursive: true, followLinks: false) .map((File file) => file.path) .where((_path) => path.extension(_path) == ".html"); } List getDartPaths(htmlPaths) { List paths = []; for (var htmlPath in htmlPaths) { var file = new File(htmlPath).readAsStringSync(); var contents = parse(file); var scripts = contents.body.querySelectorAll("script"); if (!scripts.isEmpty) { for(var script in scripts) { if (script.attributes['type'] == 'application/dart') { // Links to .dart files may not always be in the same directory as // the .html file. The following line computes the correct path of // the .dart file. // So, given a web/app/index.html file that contains a // ================================================ FILE: html5/web/appcache/beginner/offline.html ================================================ Appcache for Beginners : Offline

This application is offline.

================================================ FILE: html5/web/canvas/hidpi/hidpi.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ html, body { font-family: Helvetica, sans-serif; } h1 { margin: 2em 0 0.5em 0; font-size: 16px; } /* Do the typical thing of setting the image to be a proportion of its natural dimensions. */ #pic { width: 300px; height: 90px; } #canvas { border: 1px solid #CCC; } ================================================ FILE: html5/web/canvas/hidpi/hidpi.dart ================================================ // Copyright (c) 2012, 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 COPYING file. // This is a port of "High DPI Canvas" to Dart. // See: http://www.html5rocks.com/en/tutorials/canvas/hidpi/ import 'dart:html'; void drawImage(CanvasElement canvas, ImageElement image, {bool auto: true, srcX: 0, srcY: 0, srcW: null, srcH: null, desX: null, desY: null, desW: null, desH: null}) { if (srcW == null) srcW = image.naturalWidth; if (srcH == null) srcH = image.naturalHeight; if (desX == null) desX = srcX; if (desY == null) desY = srcY; if (desW == null) desW = srcW; if (desH == null) desH = srcH; CanvasRenderingContext2D context = canvas.getContext("2d"); num devicePixelRatio = window.devicePixelRatio; num backingStoreRatio = context.backingStorePixelRatio; num ratio = devicePixelRatio / backingStoreRatio; if (auto && devicePixelRatio != backingStoreRatio) { num oldWidth = canvas.width; num oldHeight = canvas.height; canvas.width = (oldWidth * ratio).round(); canvas.height = (oldHeight * ratio).round(); canvas.style.width = "${oldWidth}px"; canvas.style.height = "${oldHeight}px"; context.scale(ratio, ratio); } context.drawImageScaledFromSource(image as CanvasImageSource, srcX, srcY, srcW, srcH, desX, desY, desW, desH); } void main() { CanvasElement canvas = querySelector("#canvas"); ImageElement pic = querySelector("#pic"); drawImage(canvas, pic, desX: 10, desY: 10, desW: 300, desH: 90); } ================================================ FILE: html5/web/canvas/hidpi/hidpi.html ================================================ Canvas Test

Original Image:

Canvas Version:

================================================ FILE: html5/web/canvas/imagefilters/README.md ================================================ ## Using Image Filters with Canvas A port of the examples used in the [Image Filters with Canvas](http://www.html5rocks.com/en/tutorials/canvas/imagefilters/) article by Ilmari Heikkinen, originally published on HTML5Rocks. The article describes how to use image filters with an HTML5 Canvas element. It explains how to process pixels, run simple filters, and blur, sharpen and emboss an image using convolution filters. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/canvas/imagefilters/imagefilters.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ body { background-color: #F8F8F8; font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: normal; line-height: 1.2em; margin: 15px; } p { color: #333; } figure { width: 700px; margin: 50px auto; padding-left: 50px; } #container { width: 100%; border: 1px solid #ccc; background-color: #fff; } .show { display: inline; } .hide { display: none; } ================================================ FILE: html5/web/canvas/imagefilters/imagefilters.dart ================================================ // Copyright (c) 2012, 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 COPYING file. // This is a port of "Image Filters with Canvas" to Dart. // See: http://www.html5rocks.com/en/tutorials/canvas/imagefilters/ import 'dart:html'; import 'dart:math'; import 'dart:typed_data'; class Filters { ImageData pixels; Filters(ImageElement img) { pixels = getPixels(img); } // Get image pixels from image element. ImageData getPixels(ImageElement img) { var canvas = new CanvasElement(width: img.width, height: img.height); CanvasRenderingContext2D context = canvas.getContext('2d'); context.drawImage(img, 0, 0); return context.getImageData(0, 0, canvas.width, canvas.height); } // Create a temporary canvas to apply the filter to. ImageData createTempCanvas(int width, int height) { var tempCanvas = new CanvasElement(width: width, height: height); CanvasRenderingContext2D tempContext = tempCanvas.getContext('2d'); return tempContext.createImageData(width, height); } // Apply grayscale filter. ImageData grayscale() { var d = pixels.data; for (var i = 0; i < d.length; i += 4) { var r = d[i]; var g = d[i+1]; var b = d[i+2]; // CIE luminance for the RGB var v = (0.2126 * r).toInt() + (0.7152 * g).toInt() + (0.0722 * b).toInt(); d[i] = d[i + 1] = d[i + 2] = v; } return pixels; } // Apply brightness filter. ImageData brightness(int brightAdj) { var d = pixels.data; for (var i=0; i= thresholdVal) ? 255 : 0; d[i] = d[i + 1] = d[i + 2] = v; } return pixels; } // Apply convolution filter. ImageData convolve(List weights, [bool opaque = false]) { var alphaFac = opaque ? 1 : 0; var side = (sqrt(weights.length).toInt()); var halfSide = side ~/ 2; var d = pixels.data; var width = pixels.width; var height = pixels.height; var output = createTempCanvas(width, height); var dest = output.data; //Loop over the image. for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var r = 0.0, g = 0.0, b = 0.0, a = 0.0; var destOff = (y * width + x) * 4; //Now loop over the filter mask. for (var fy = 0; fy < side; fy++) { for (var fx = 0; fx < side; fx++) { var srcy = min(height - 1, max(0, y + fy - halfSide)); var srcx = min(width - 1, max(0, x + fx - halfSide)); var srcOff = (srcy * width + srcx) * 4; var weight = weights[(fy * side + fx)]; r += d[srcOff] * weight; g += d[srcOff + 1] * weight; b += d[srcOff + 2] * weight; a += d[srcOff + 3] * weight; } } dest[destOff] = r.toInt(); dest[destOff + 1] = g.toInt(); dest[destOff + 2] = b.toInt(); dest[destOff + 3] = (a + alphaFac * (255 - a)).toInt(); } } return output; } // Apply Sobel filter. ImageData sobel(List hWeights, List vWeights) { var grayPixels = grayscale(); var vpixels = convolveFloat32(grayPixels, vWeights); var hpixels = convolveFloat32(grayPixels, hWeights); var id = createTempCanvas(vpixels.width, vpixels.height); for (var i = 0; i < id.data.length; i += 4) { var v = vpixels.data[i].abs(); id.data[i] = v.toInt(); var h = hpixels.data[i].abs(); id.data[i + 1] = h.toInt(); id.data[i + 2] = ((v + h) / 4).toInt(); id.data[i + 3] = 255; } return id; } // Apply convolution filter and return data as a double array. ImageDataFloat32 convolveFloat32(ImageData pixels, List weights, {bool opaque: false}) { var alphaFac = opaque ? 1 : 0; var side = (sqrt(weights.length).toInt()); var halfSide = side ~/ 2; var d = pixels.data; var width = pixels.width; var height = pixels.height; //Create data structure to store the filtered data of type double. var output = new ImageDataFloat32(new Float32List(width * height * 4), width, height); var dest = output.data; //Loop over the image. for (var y = 0; y < height; y++) { for (var x = 0; x < width; x++) { var r = 0.0, g = 0.0, b = 0.0, a = 0.0; var destOff = (y * width + x) * 4; //Now loop over the filter mask. for (var fy = 0; fy < side; fy++) { for (var fx = 0; fx < side; fx++) { var srcy = min(height - 1, max(0, y + fy - halfSide)); var srcx = min(width - 1, max(0, x + fx - halfSide)); var srcOff = (srcy * width + srcx) * 4; var weight = weights[(fy * side + fx)]; r += d[srcOff] * weight; g += d[srcOff + 1] * weight; b += d[srcOff + 2] * weight; a += d[srcOff + 3] * weight; } } dest[destOff] = r; dest[destOff + 1] = g; dest[destOff + 2] = b; dest[destOff + 3] = (a + alphaFac * (255 - a)); } } return output; } } // Create a class to hold image data in a 32 bit float array. class ImageDataFloat32 { final Float32List data; final width, height; ImageDataFloat32(this.data, this.width, this.height); } void main() { final brightAdj = 40; final thresholdVal = 128; final sharpenMask = [0, -1, 0, -1, 5, -1, 0, -1, 0]; final blurMask = [1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9, 1/9]; final hSobelMask = [-1, 0, 1, -2, 0, 2, -1, 0, 1]; final vSobelMask = [-1,-2,-1, 0, 0, 0, 1, 2, 1]; var img = querySelector('.orig'); window.onLoad.listen((e) => populateImages(img)); // Click listener for grayscale. querySelector('[name = "grayscale"]').onClick.listen( (e) => toggleFilter('grayscale', () => new Filters(img).grayscale())); // Click listener for brightness. querySelector('[name = "brightness"]').onClick.listen( (e) => toggleFilter('brightness', () => new Filters(img).brightness(brightAdj))); // Click listener for threshold. querySelector('[name = "threshold"]').onClick.listen( (e) => toggleFilter('threshold', () => new Filters(img).threshold(thresholdVal))); // Click listener for sharpen. querySelector('[name = "sharpen"]').onClick.listen( (e) => toggleFilter('sharpen', () => new Filters(img).convolve(sharpenMask))); // Click listener for blur. querySelector('[name = "blur"]').onClick.listen( (e) => toggleFilter('blur', () => new Filters(img).convolve(blurMask))); // Click listener for sobel. querySelector('[name = "sobel"]').onClick.listen( (e) => toggleFilter('sobel', () => new Filters(img).sobel(hSobelMask, vSobelMask))); // Click listener for custom. querySelector('[name = "custom"]').onClick.listen( (e) => toggleFilter('custom', () { var matrix = querySelector('#customMatrix').querySelectorAll('input'); var mask = new List(); for (var i = 0; i < matrix.length; i++) { mask.add(double.parse(matrix[i].value)); } return new Filters(img).convolve(mask, true); })); } // Add copies of the original image to each canvas element. void populateImages(ImageElement img) { var canvases = querySelectorAll('canvas'); for(var i = 0; i < canvases.length; i++) { var canvas = canvases[i]; canvas.parent.insertBefore(img.clone(true), canvas); canvas.classes.add('hide'); } } // Put the filtered image back to its original (unfiltered) condition. void restoreContent(String id) { var canvas = querySelector('#$id'); canvas.classes.remove('show'); canvas.classes.add('hide'); canvas.previousElementSibling.classes.remove('hide'); canvas.previousElementSibling.classes.add('show'); canvas.parent.querySelector('button').text = 'apply $id filter'; } // Show the filtered image. void filterImage(String id, ImageData pixels) { CanvasElement canvas = querySelector('#$id'); canvas.width = pixels.width; canvas.height = pixels.height; canvas.getContext('2d') as CanvasRenderingContext2D ..putImageData(pixels, 0, 0); canvas.previousElementSibling.classes.remove('show'); canvas.previousElementSibling.classes.add('hide'); canvas.classes.remove('hide'); canvas.classes.add('show'); canvas.parent.querySelector('button').text = 'remove $id filter'; } // Handle applying the filter to the image. typedef ImageData ApplyFilter(); void toggleFilter(String id, ApplyFilter filter) { if (querySelector('#$id').previousElementSibling.classes.contains('hide')) { restoreContent(id); } else { filterImage(id, filter()); } } ================================================ FILE: html5/web/canvas/imagefilters/index.html ================================================ Image Filters in Dart

Image Filters in Dart

Image Filters with Canvas

The original test image



================================================ FILE: html5/web/dnd/basics/README.md ================================================ ## Basic Drag and Drop A port of the Drag and Drop example used in the [Native HTML5 Drag and Drop](http://www.html5rocks.com/en/tutorials/dnd/basics/) article by Eric Bidelman, originally published on HTML5Rocks. HTML5 Drag and drop (DnD) is event-based way of making an element draggable on a page. Native browser support for this feature means faster, more responsive web apps. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/dnd/basics/basics.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ body { background-color: #F8F8F8; font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: normal; line-height: 1.2em; margin: 15px; } /* Prevent the text contents of draggable elements from being selectable. */ [draggable] { -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; user-select: none; } .column { background-color: #ccc; -webkit-border-radius: 10px; -moz-border-radius: 10px; -ms-border-radius: 10px; border: 2px solid #666; border-radius: 10px; -webkit-box-shadow: inset 0 0 3px #000; -ms-box-shadow: inset 0 0 3px #000; box-shadow: inset 0 0 3px #000; cursor: move; height: 150px; float: left; margin-right: 5px; text-align: center; -webkit-transition: -webkit-transform 0.2s ease-out; -moz-transition: -moz-transform 0.2s ease-out; -ms-transition: -moz-transform 0.2s ease-out; transition: transform 0.2s ease-out; width: 150px; } .column header { background: -moz-linear-gradient(left center, rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); background: -webkit-linear-gradient(linear, left top, right top, color-stop(0, rgb(0, 0, 0)), color-stop(0.5, rgb(79, 79, 79)), color-stop(1, rgb(21, 21, 21))); background: -webkit-linear-gradient(left center, rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); background: -ms-linear-gradient(left center, rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); border-bottom: 1px solid #ddd; -webkit-border-top-left-radius: 10px; -moz-border-radius-topleft: 10px; -ms-border-radius-topleft: 10px; border-top-left-radius: 10px; -webkit-border-top-right-radius: 10px; -moz-border-radius-topright: 10px; -ms-border-radius-topright: 10px; border-top-right-radius: 10px; box-shadow: 5px; color: #fff; padding: 5px; text-shadow: #000 0 1px; } .column.over { border: 2px dashed #000; } .column.moving { opacity: 0.25; -webkit-transform: scale(0.8); -moz-transform: scale(0.8); -ms-transform: scale(0.8); transform: scale(0.8); } ================================================ FILE: html5/web/dnd/basics/basics.dart ================================================ // Copyright (c) 2012, 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 COPYING file. // This is a port of "Native HTML5 Drag and Drop" to Dart. // See: http://www.html5rocks.com/en/tutorials/dnd/basics/ import 'dart:html'; class Basics { Element _dragSourceEl; void start() { var cols = document.querySelectorAll('#columns .column'); for (var col in cols) { col.onDragStart.listen(_onDragStart); col.onDragEnd.listen(_onDragEnd); col.onDragEnter.listen(_onDragEnter); col.onDragOver.listen(_onDragOver); col.onDragLeave.listen(_onDragLeave); col.onDrop.listen(_onDrop); } } void _onDragStart(MouseEvent event) { Element dragTarget = event.target; dragTarget.classes.add('moving'); _dragSourceEl = dragTarget; event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/html', dragTarget.innerHtml); } void _onDragEnd(MouseEvent event) { Element dragTarget = event.target; dragTarget.classes.remove('moving'); var cols = document.querySelectorAll('#columns .column'); for (var col in cols) { col.classes.remove('over'); } } void _onDragEnter(MouseEvent event) { Element dropTarget = event.target; dropTarget.classes.add('over'); } void _onDragOver(MouseEvent event) { // This is necessary to allow us to drop. event.preventDefault(); event.dataTransfer.dropEffect = 'move'; } void _onDragLeave(MouseEvent event) { Element dropTarget = event.target; dropTarget.classes.remove('over'); } void _onDrop(MouseEvent event) { // Stop the browser from redirecting. event.stopPropagation(); // Don't do anything if dropping onto the same column we're dragging. Element dropTarget = event.target; if (_dragSourceEl != dropTarget) { // Set the source column's HTML to the HTML of the column we dropped on. _dragSourceEl.innerHtml = dropTarget.innerHtml; dropTarget.innerHtml = event.dataTransfer.getData('text/html'); } } } void main() { var basics = new Basics(); basics.start(); } ================================================ FILE: html5/web/dnd/basics/index.html ================================================ Drag and Drop: Basics
A
B
C
================================================ FILE: html5/web/file/dndfiles/README.md ================================================ ## Using the File APIs A Dart port of the Files API examples used in the [Reading files in JavaScript using the File APIs](http://www.html5rocks.com/en/tutorials/file/dndfiles/) article by Eric Bidelman, originally published on HTML5Rocks. The examples show how to select a file using a form input, or using drag and drop. See how you can slice a file in separate byte range chunks for efficient uploading, and monitor progress while uploading a file. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/file/dndfiles/dndfiles.css ================================================ /* Copyright (c) 2012, 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. */ body { color: #333; font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: normal; line-height: 1.2em; margin: 15px; } output { display: block; } #byte-content { margin: 5px 0; max-height: 200px; overflow-x: hidden; overflow-y: auto; } #byte-range { margin-top: 5px; } #drop-zone { border: 2px dashed #bbb; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; color: #bbb; font-size: 20pt; font-weight: bold; padding: 25px; text-align: center; } #drop-zone.hover { background-color: #def; border-color: #777; color: #777; } #progress-bar { background-color: #9cf; border: 1px solid #000; font-size: 14px; margin: 10px 0; opacity: 0; -webkit-transition: opacity 0.5s linear; -moz-transition: opacity 0.5s linear; -o-transition: opacity 0.5s linear; transition: opacity 0.5s linear; padding: 3px; } #progress-bar.loading { opacity: 1.0; } .thumb { border: 1px solid #000; height: 75px; margin: 10px 5px 0 0; } ================================================ FILE: html5/web/file/dndfiles/dndfiles.dart ================================================ // Copyright (c) 2012, 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 is a port of "Reading Files in JavaScript Using the File APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ import 'dart:convert' show HtmlEscape; import 'dart:html'; class DndFiles { FormElement _readForm; InputElement _fileInput; Element _dropZone; OutputElement _output; HtmlEscape sanitizer = new HtmlEscape(); DndFiles() { _output = document.querySelector('#list'); _readForm = document.querySelector('#read'); _fileInput = document.querySelector('#files'); _fileInput.onChange.listen((e) => _onFileInputChange()); _dropZone = document.querySelector('#drop-zone'); _dropZone.onDragOver.listen(_onDragOver); _dropZone.onDragEnter.listen((e) => _dropZone.classes.add('hover')); _dropZone.onDragLeave.listen((e) => _dropZone.classes.remove('hover')); _dropZone.onDrop.listen(_onDrop); } void _onDragOver(MouseEvent event) { event.stopPropagation(); event.preventDefault(); event.dataTransfer.dropEffect = 'copy'; } void _onDrop(MouseEvent event) { event.stopPropagation(); event.preventDefault(); _dropZone.classes.remove('hover'); _readForm.reset(); _onFilesSelected(event.dataTransfer.files); } void _onFileInputChange() { _onFilesSelected(_fileInput.files); } void _onFilesSelected(List files) { _output.nodes.clear(); var list = new Element.tag('ul'); for (var file in files) { var item = new Element.tag('li'); // If the file is an image, read and display its thumbnail. if (file.type.startsWith('image')) { var thumbHolder = new Element.tag('span'); var reader = new FileReader(); reader.onLoad.listen((e) { var thumbnail = new ImageElement(src: reader.result); thumbnail.classes.add('thumb'); thumbnail.title = sanitizer.convert(file.name); thumbHolder.nodes.add(thumbnail); }); reader.readAsDataUrl(file); item.nodes.add(thumbHolder); } // For all file types, display some properties. var properties = new Element.tag('span'); properties.innerHtml = (new StringBuffer('') ..write(sanitizer.convert(file.name)) ..write(' (') ..write(file.type != null ? sanitizer.convert(file.type) : 'n/a') ..write(') ') ..write(file.size) ..write(' bytes') // TODO(jason9t): Re-enable this when issue 5070 is resolved. // http://code.google.com/p/dart/issues/detail?id=5070 // ..add(', last modified: ') // ..add(file.lastModifiedDate != null ? // file.lastModifiedDate.toLocal().toString() : // 'n/a') ).toString(); item.nodes.add(properties); list.nodes.add(item); } _output.nodes.add(list); } } void main() { new DndFiles(); } ================================================ FILE: html5/web/file/dndfiles/dndfiles.html ================================================ Reading Files Using the File APIs

Using Form Input, Drag and Drop, and Reading Files

Drop files here
================================================ FILE: html5/web/file/dndfiles/index.html ================================================ Reading Files Using the File APIs

Using the File APIs: Choose an Example

  1. Using Form Input, Drag and Drop, and Reading Files
  2. Slicing a File
  3. Monitoring the Progress of a Read
================================================ FILE: html5/web/file/dndfiles/monitoring.dart ================================================ // Copyright (c) 2012, 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 is a port of "Reading Files in JavaScript Using the File APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ import 'dart:html'; import 'dart:math'; import 'dart:async'; class Monitoring { InputElement _fileInput; Element _progressBar; FileReader _reader; Monitoring() { _progressBar = querySelector('#progress-bar'); _fileInput = document.querySelector('#files'); _fileInput.onChange.listen((e) => _onFilesSelected()); var cancelButton = querySelector('#cancel-read'); cancelButton.onClick.listen((e) => _onCancel()); } void _setProgress(int value) { value = min(100, max(0, value)); _progressBar.style.width = '${value}%'; _progressBar.text = '${value}%'; if (value == 0 || value == 100) { new Timer(const Duration(milliseconds: 2000), () => _progressBar.classes.remove('loading')); } } void _onFilesSelected() { // Reset progress indicator on new file selection. _setProgress(0); _progressBar.classes.remove('loading'); // Set up handlers and begin reading the file. var file = _fileInput.files[0]; _reader = new FileReader(); _reader.onError.listen((e) => _onError()); _reader.onProgress.listen(_onProgress); _reader.onAbort.listen((e) => window.alert('File read cancelled.')); _reader.onLoadStart.listen((e) => _progressBar.classes.add('loading')); _reader.onLoad.listen((e) => _setProgress(100)); _reader.readAsText(file); } void _onCancel() { if (_reader != null) { _reader.abort(); } } void _onProgress(ProgressEvent event) { if (event.lengthComputable) { var percentLoaded = (100 * event.loaded / event.total).round().toInt(); _setProgress(percentLoaded); } } void _onError() { switch(_reader.error.code) { case FileError.NOT_FOUND_ERR: window.alert('File not found!'); break; case FileError.NOT_READABLE_ERR: window.alert('File is not readable.'); break; case FileError.ABORT_ERR: break; // no-op. default: window.alert('An error occurred reading this file.'); break; } } } void main() { new Monitoring(); } ================================================ FILE: html5/web/file/dndfiles/monitoring.html ================================================ Reading Files Using the File APIs

Monitoring the Progress of a Read

0%
================================================ FILE: html5/web/file/dndfiles/slicing.dart ================================================ // Copyright (c) 2012, 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 is a port of "Reading Files in JavaScript Using the File APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ import 'dart:html'; class Slicing { InputElement _fileInput; Element _content; Element _byteRange; Slicing() { _content = querySelector('#byte-content'); _byteRange = querySelector('#byte-range'); _fileInput = querySelector('#files'); _fileInput.onChange.listen((e) { _content.text = ''; _byteRange.text = ''; }); var buttons = querySelector('#read-bytes-buttons'); buttons.onClick.listen(_onClick); } void _onClick(MouseEvent event) { Element clicked = event.target; if (clicked is ButtonElement) { var start = clicked.attributes['data-startbyte']; var end = clicked.attributes['data-endbyte']; _readBlob( start != null ? int.parse(start) : null, end != null ? int.parse(end) : null); } } void _readBlob([int startByte, int endByte]) { var files = _fileInput.files; if (files.length == 0) { window.alert('Please select a file!'); return; } var file = files[0]; var start = startByte != null ? startByte : 0; var end = endByte != null ? endByte : file.size; var reader = new FileReader(); reader.onLoad.listen((e) { _content.text = reader.result; _byteRange.text = 'Read bytes ${start + 1} - ${end + 1} of ${file.size}.'; }); var slice = file.slice(start, end); reader.readAsDataUrl(slice); } } void main() { new Slicing(); } ================================================ FILE: html5/web/file/dndfiles/slicing.html ================================================ Reading Files Using the File APIs

Slicing a File

================================================ FILE: html5/web/file/filesystem/README.md ================================================ ## Exploring the FileSystem APIs A port of the FileSystem example used in the [Exploring the FileSystem APIs](http://www.html5rocks.com/en/tutorials/file/filesystem/) article by Eric Bidelman, originally published on HTML5Rocks. With the FileSystem API, a web app can create, read, navigate, and write to a sandboxed section of the user's local file system. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/file/filesystem/filesystem.css ================================================ /* Copyright (c) 2012, 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. */ .example { padding: 10px; border: 1px solid #CCC; } #example-list-fs ul { padding-left: 0; } #example-list-fs li { list-style: none; } #example-list-fs img { vertical-align: middle; } button { padding: 5px 8px; cursor: pointer; text-shadow: 1px 1px white; font-weight: 700; font-size: 10pt; } body { font: 14px Arial; } ================================================ FILE: html5/web/file/filesystem/filesystem.dart ================================================ // Copyright (c) 2012, 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 is a port of "Exploring the FileSystem APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/filesystem/ import 'dart:convert' show HtmlEscape; import 'dart:html'; class FileSystemExample { FileSystem _filesystem; Element _fileList; HtmlEscape sanitizer = new HtmlEscape(); FileSystemExample() { _fileList = querySelector('#example-list-fs-ul'); window.requestFileSystem(1024 * 1024, persistent: false) .then(_requestFileSystemCallback, onError: _handleError); } void _requestFileSystemCallback(FileSystem filesystem) { _filesystem = filesystem; querySelector('#add-button').onClick.listen((e) => _addFiles()); querySelector('#list-button').onClick.listen((e) => _listFiles()); querySelector('#remove-button').onClick.listen((e) => _removeFiles()); } void _handleError(FileError e) { var msg = ''; switch (e.code) { case FileError.QUOTA_EXCEEDED_ERR: msg = 'QUOTA_EXCEEDED_ERR'; break; case FileError.NOT_FOUND_ERR: msg = 'NOT_FOUND_ERR'; break; case FileError.SECURITY_ERR: msg = 'SECURITY_ERR'; break; case FileError.INVALID_MODIFICATION_ERR: msg = 'INVALID_MODIFICATION_ERR'; break; case FileError.INVALID_STATE_ERR: msg = 'INVALID_STATE_ERR'; break; default: msg = 'Unknown Error'; break; } querySelector("#example-list-fs-ul").text = "Error: $msg"; } void _addFiles() { _filesystem.root.createFile('log.txt').catchError(_handleError); _filesystem.root.createFile('song.mp3').catchError(_handleError); _filesystem.root.createDirectory('mypictures').catchError(_handleError); _fileList.text = 'Files created.'; } void _listFiles() { var dirReader = _filesystem.root.createReader(); dirReader.readEntries().then((entries) { if (entries.length == 0) { _fileList.text = 'Filesystem is empty.'; } else { _fileList.text = ''; } var fragment = document.createDocumentFragment(); entries.forEach((entry) { var img = entry.isDirectory ? '' : ''; var li = new Element.tag("li"); li.innerHtml = "$img${sanitizer.convert(entry.name)}"; fragment.nodes.add(li); }); _fileList.nodes.add(fragment); }, onError: _handleError); } void _removeFiles() { var dirReader = _filesystem.root.createReader(); dirReader.readEntries().then((entries) { entries.forEach((entry) { if (entry.isDirectory) { entry.removeRecursively().then((_) {}, onError: _handleError); } else { entry.remove().then((_) {}, onError: _handleError); } }); _fileList.text = 'Directory emptied.'; }, onError: _handleError); } } void main() { new FileSystemExample(); } ================================================ FILE: html5/web/file/filesystem/index.html ================================================ Filesystem
    ================================================ FILE: html5/web/file/terminal/README.md ================================================ ## A Terminal Emulator that uses the FileSystem APIs A port of the Terminal example used in the [Exploring the FileSystem APIs](http://www.html5rocks.com/en/tutorials/file/filesystem/) article by Eric Bidelman, originally published on HTML5Rocks. With the FileSystem API, a web app can create, read, navigate, and write to a sandboxed section of the user's local file system. This example simulates a UNIX terminal, and replicates common UNIX filesystem operations such as `cd`, `mkdir`, `rm`, `open`, and `cat` using the FileSystem API. To add content, open the app, then drag and drop files from your desktop onto the terminal window. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/file/terminal/index.html ================================================ TerminalFilesystem

    TerminalFilesystem

    $>
    ================================================ FILE: html5/web/file/terminal/terminal.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ ::selection { background: #FF5E99; } html, body { width: 100%; height: 100%; margin: 0; } body { font-size: 12px; font-family: Inconsolata, monospace; color: white; background-color: black; } .dropping { background-image: -webkit-gradient( linear, left bottom, left top, color-stop(0.13, rgb(209,144,23)), color-stop(0.57, rgb(251,173,51)), color-stop(0.79, rgb(255,208,77)) ); background-image: -moz-linear-gradient( center bottom, rgb(209,144,23) 13%, rgb(251,173,51) 57%, rgb(255,208,77) 79% ); } #container { padding: 1em 1.5em 1em 1em; } #container output { clear: both; width: 100%; } #container output h3 { margin: 0; } #container output pre { margin: 0; } .input-line { display: -webkit-box; -webkit-box-orient: horizontal; -webkit-box-align: stretch; display: -moz-box; -moz-box-orient: horizontal; -moz-box-align: stretch; display: box; box-orient: horizontal; box-align: stretch; clear: both; } .input-line > div:nth-child(2) { -webkit-box-flex: 1; -moz-box-flex: 1; box-flex: 1; } .prompt { white-space: nowrap; color: green; margin-right: 7px; display: -webkit-box; -webkit-box-pack: center; -webkit-box-orient: vertical; display: -moz-box; -moz-box-pack: center; -moz-box-orient: vertical; display: box; box-pack: center; box-orient: vertical; -webkit-user-select: none; -moz-user-select: none; user-select: none; } .cmdline { outline: none; background-color: transparent; margin: 0; width: 100%; font: inherit; border: none; color: inherit; } .folder { color: blue; } .ls-files { height: 45px; /* Default, but changed by js depending on length of filename */ -webkit-column-width: 100px; -moz-column-width: 100px; -o-column-width: 100px; column-width: 100px; } /* Themes */ body.cream { color: black; background-color: #fffff3; } .cream .prompt { color: purple; } .cream .cmdline { color: black; } ================================================ FILE: html5/web/file/terminal/terminal.dart ================================================ // Copyright (c) 2012, 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 is a port of "Exploring the FileSystem APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/filesystem/ part of terminal_filesystem; class Terminal { FileSystem fs; DirectoryEntry cwd; String cmdLineContainer; String outputContainer; String cmdLineInput; OutputElement output; InputElement input; DivElement cmdLine; String version = '0.0.1'; List themes = ['default', 'cream']; List history = []; int historyPosition = 0; Map cmds; HtmlEscape sanitizer = new HtmlEscape(); Terminal(this.cmdLineContainer, this.outputContainer, this.cmdLineInput) { cmdLine = document.querySelector(cmdLineContainer); output = document.querySelector(outputContainer); input = document.querySelector(cmdLineInput); // Always force text cursor to end of input line. window.onClick.listen((event) => cmdLine.focus()); // Trick: Always force text cursor to end of input line. cmdLine.onClick.listen((event) => input.value = input.value); // Handle up/down key presses for shell history and enter for new command. cmdLine.onKeyDown.listen(historyHandler); cmdLine.onKeyDown.listen(processNewCommand); } void historyHandler(KeyboardEvent event) { var histtemp = ""; int upArrowKey = 38; int downArrowKey = 40; /* keyCode == up-arrow || keyCode == down-arrow */ if (event.keyCode == upArrowKey || event.keyCode == downArrowKey) { event.preventDefault(); // Up or down if (historyPosition < history.length) { history[historyPosition] = input.value; } else { histtemp = input.value; } } if (event.keyCode == upArrowKey) { // Up-arrow keyCode historyPosition--; if (historyPosition < 0) { historyPosition = 0; } } else if (event.keyCode == downArrowKey) { // Down-arrow keyCode historyPosition++; if (historyPosition >= history.length) { historyPosition = history.length - 1; } } /* keyCode == up-arrow || keyCode == down-arrow */ if (event.keyCode == upArrowKey || event.keyCode == downArrowKey) { // Up or down input.value = history[historyPosition] != null ? history[historyPosition] : histtemp; } } void processNewCommand(KeyboardEvent event) { int enterKey = 13; int tabKey = 9; if (event.keyCode == tabKey) { event.preventDefault(); } else if (event.keyCode == enterKey) { if (!input.value.isEmpty) { history.add(input.value); historyPosition = history.length; } // Move the line to output and remove id's. DivElement line = input.parent.parent.clone(true); line.attributes.remove('id'); line.classes.add('line'); InputElement cmdInput = line.querySelector(cmdLineInput); cmdInput.attributes.remove('id'); cmdInput.autofocus = false; cmdInput.readOnly = true; output.children.add(line); String cmdline = input.value; input.value = ""; // clear input // Parse out command, args, and trim off whitespace. List args; String cmd = ""; if (!cmdline.isEmpty) { cmdline.trim(); args = sanitizer.convert(cmdline).split(' '); cmd = args[0]; args.removeRange(0, 1); } // Function look up if (cmds[cmd] is Function) { cmds[cmd](cmd, args); } else { writeOutput('${sanitizer.convert(cmd)}: command not found'); } window.scrollTo(0, window.innerHeight); } } void initializeFilesystem(bool persistent, int size) { cmds = { 'clear': clearCommand, 'help': helpCommand, 'version': versionCommand, 'cat': catCommand, 'cd': cdCommand, 'date': dateCommand, 'ls': lsCommand, 'mkdir': mkdirCommand, 'mv': mvCommand, 'cp': cpCommand, 'open': openCommand, 'pwd': pwdCommand, 'rm': rmCommand, 'rmdir': rmdirCommand, 'theme': themeCommand, 'who': whoCommand }; writeOutput('
    Welcome to ${sanitizer.convert(document.title)}! (v$version)
    '); writeOutput(new DateTime.now().toLocal().toString()); writeOutput('

    Documentation: type "help"

    '); window.requestFileSystem(size, persistent: persistent) .then(filesystemCallback, onError: errorHandler); } void filesystemNotInitialized(String cmd, List args) { writeOutput('
    ${sanitizer.convert(cmd)}: not available since filesystem was not initialized
    '); } void filesystemCallback(FileSystem filesystem) { fs = filesystem; if (fs is FileSystem) { cwd = fs.root; } else { cmds['cat'] = filesystemNotInitialized; cmds['cd'] = filesystemNotInitialized; cmds['ls'] = filesystemNotInitialized; cmds['mkdir'] = filesystemNotInitialized; cmds['mv'] = filesystemNotInitialized; cmds['cp'] = filesystemNotInitialized; cmds['open'] = filesystemNotInitialized; cmds['pwd'] = filesystemNotInitialized; cmds['rm'] = filesystemNotInitialized; cmds['rmdir'] = filesystemNotInitialized; } // Attempt to create a folder to test if we can. cwd.createDirectory('testquotaforfsfolder') .then((DirectoryEntry dirEntry) { dirEntry.remove().then((_) {}); // If successfully created, just delete it. }, onError: (error) { if (error.code == FileError.QUOTA_EXCEEDED_ERR) { writeOutput('ERROR: Write access to the filesystem is ' 'unavailable. Are you running Google Chrome with ' '--unlimited-quota-for-files?'); } else { errorHandler(error); } }); } void errorHandler(error) { var msg = ''; switch (error.code) { case FileError.QUOTA_EXCEEDED_ERR: msg = 'QUOTA_EXCEEDED_ERR'; break; case FileError.NOT_FOUND_ERR: msg = 'NOT_FOUND_ERR'; break; case FileError.SECURITY_ERR: msg = 'SECURITY_ERR'; break; case FileError.INVALID_MODIFICATION_ERR: msg = 'INVALID_MODIFICATION_ERR'; break; case FileError.INVALID_STATE_ERR: msg = 'INVALID_STATE_ERR'; break; case FileError.TYPE_MISMATCH_ERR: msg = 'TYPE_MISMATCH_ERR'; break; default: msg = 'FileError = ${error.code}: Error not handled'; break; }; writeOutput('
    Error: ${sanitizer.convert(msg)}
    '); } void invalidOpForEntryType(FileError error, String cmd, String dest) { switch (error.code) { case FileError.NOT_FOUND_ERR: writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(dest)}: No such file or directory
    '); break; case FileError.INVALID_STATE_ERR: writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(dest)}: Not a directory
    '); break; case FileError.INVALID_MODIFICATION_ERR: writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(dest)}: File already exists
    '); break; default: errorHandler(error); break; } } void setTheme([String theme='default']) { if (theme == null || theme == 'default') { window.localStorage.remove('theme'); document.body.classes.clear(); } else { document.body.classes.add(theme); window.localStorage['theme'] = theme; } } void addDroppedFiles(List files) { files.forEach((file) { cwd.createFile(file.name, exclusive: true) .then((FileEntry fileEntry) { fileEntry.createWriter().then((FileWriter fileWriter) { fileWriter.onError.listen(errorHandler); fileWriter.write(file); }, onError: errorHandler); }, onError: errorHandler); }); } void read(String cmd, String path, var callback) { cwd.getFile(path).then((FileEntry fileEntry) { fileEntry.file().then((file) { var reader = new FileReader(); reader.onLoadEnd.listen((ProgressEvent event) => callback(reader.result)); reader.readAsText(file); }, onError: errorHandler); }, onError: (error) { if (error.code == FileError.INVALID_STATE_ERR) { writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(path)}): is a directory
    '); } else if (error.code == FileError.NOT_FOUND_ERR) { writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(path)}: No such file or directory
    '); } else { errorHandler(error); } }); } void clearCommand(String cmd, List args) { output.innerHtml = ''; } void helpCommand(String cmd, List args) { StringBuffer sb = new StringBuffer(); sb.write('
    '); cmds.keys.forEach((key) => sb.write('$key
    ')); sb.write('
    '); sb.write('

    Add files by dragging them from your desktop.

    '); writeOutput(sb.toString()); } void versionCommand(String cmd, List args) { writeOutput("$version"); } void catCommand(String cmd, List args) { if (args.length >= 1) { var fileName = args[0]; read(cmd, fileName, (result) => writeOutput('
    ${sanitizer.convert(result)}
    ')); } else { writeOutput('usage: ${sanitizer.convert(cmd)} filename'); } } void cdCommand(String cmd, List args) { var dest = args.join(' ').trim(); if (dest.isEmpty) { dest = '/'; } cwd.getDirectory(dest) .then((DirectoryEntry dirEntry) { cwd = dirEntry; writeOutput('
    ${sanitizer.convert(dirEntry.fullPath)}
    '); }, onError: (FileError error) { invalidOpForEntryType(error, cmd, dest); }); } void dateCommand(String cmd, var args) { writeOutput(new DateTime.now().toLocal().toString()); } StringBuffer formatColumns(List entries) { var maxName = entries[0].name; entries.forEach((entry) { if (entry.name.length > maxName.length) { maxName = entry.name; } }); // If we have 3 or less entires, shorten the output container's height. var height = entries.length <= 3 ? 'height: ${entries.length}em;' : '${entries.length ~/ 3}em'; var colWidth = "${maxName.length}em"; StringBuffer sb = new StringBuffer(); sb.write('
    '); return sb; } void lsCommand(String cmd, List args) { void displayFiles(List entry) { if (entry.length != 0) { StringBuffer html = formatColumns(entry); entry.forEach((file) { var fileType = file.isDirectory ? 'folder' : 'file'; var span = '${sanitizer.convert(file.name)}
    '; html.write(span); }); html.write('
    '); writeOutput(html.toString()); } }; // Read contents of current working directory. According to spec, need to // keep calling readEntries() until length of result array is 0. We're // guarenteed the same entry won't be returned again. List entries = []; DirectoryReader reader = cwd.createReader(); void readEntries() { reader.readEntries() .then((List results) { if (results.length == 0) { displayFiles(entries); } else { entries.addAll(results); readEntries(); } }, onError: errorHandler); }; readEntries(); } void createDir(DirectoryEntry rootDirEntry, List folders, [String createFromDir="", String cmd=""]) { if (folders.length == 0) { return; } if (createFromDir.isEmpty) { rootDirEntry.createDirectory(folders[0]) .then((dirEntry) { // Recursively add the new subfolder if we still have a subfolder to create. if (folders.length != 0) { folders.removeAt(0); createDir(dirEntry, folders); } }, onError: errorHandler); } else { var fullPath = cwd.fullPath; cwd.getDirectory(createFromDir) .then((DirectoryEntry dirEntry) { cwd = dirEntry; // Create the folders createDir(cwd, folders); cwd.getDirectory(fullPath) .then((DirectoryEntry dirEntry) => cwd = dirEntry, onError: (FileError error) => invalidOpForEntryType(error, cmd, fullPath)); }, onError: (FileError error) => invalidOpForEntryType(error, cmd, createFromDir)); } } void mkdirCommand(String cmd, List args) { var dashP = false; var index = args.indexOf('-p'); if (index != -1) { args.removeAt(index); dashP = true; } if (args.length == 0) { writeOutput('usage: ${sanitizer.convert(cmd)} [-p] directory
    '); return; } // Create each directory passed as an argument. for (int i = 0; i < args.length; i++) { String dirName = args[i]; if (dashP) { var folders = dirName.split('/'); // Throw out './' or '/' if present on the beginning of our path. if (folders[0] == '.' || folders[0] == '') { folders.removeAt(0); } // If '/' is present then we change directories in createDir. if (dirName[0] == "/") { createDir(cwd, folders, dirName[0], cmd); } else { createDir(cwd, folders); } } else { cwd.createDirectory(dirName, exclusive: true) .then((_) {}, onError: (FileError error) { invalidOpForEntryType(error, cmd, dirName); }); } } } void updateFilename(String cmd, List args, Function action) { if (args.length != 2) { writeOutput('usage: ${sanitizer.convert(cmd)} source target
    ' '       ${sanitizer.convert(cmd)}' ' source directory/'); return; } String src = args[0]; String dest = args[1]; // Moving to a folder? (e.g. second arg ends in '/'). if (dest[dest.length - 1].endsWith('/')) { cwd.getDirectory(src) .then((DirectoryEntry srcDirEntry) { // Create blacklist for dirs we can't re-create. var create = ['.', './', '..', '../', '/'].indexOf(dest) != -1 ? false : true; if (create) { cwd.createDirectory(dest) .then((DirectoryEntry destDirEntry) => action(srcDirEntry, destDirEntry), onError: errorHandler); } else { cwd.getDirectory(dest) .then((DirectoryEntry destDirEntry) => action(srcDirEntry, destDirEntry), onError: errorHandler); } }, onError: errorHandler); } else { // Treat src/destination as files. cwd.getFile(src).then((FileEntry srcFileEntry) { srcFileEntry.getParent() .then((DirectoryEntry parentDirEntry) => action(srcFileEntry, parentDirEntry, dest), onError: errorHandler); }, onError: errorHandler); } } void cpCommand(String cmd, List args) { updateFilename(cmd, args, (srcDirEntry, destDirEntry, [name = ""]) { if (name.isEmpty) { srcDirEntry.copyTo(destDirEntry); } else { srcDirEntry.copyTo(destDirEntry, name); } }); } void mvCommand(String cmd, List args) { updateFilename(cmd, args, (srcDirEntry, destDirEntry, [name = ""]) { if (name.isEmpty) { srcDirEntry.moveTo(destDirEntry); } else { srcDirEntry.moveTo(destDirEntry, name); } }); } void openCommand(String cmd, List args) { //var fileName = Strings.join(args, ' ').trim(); if (args.length == 0) { writeOutput('usage: ${sanitizer.convert(cmd)} [filenames]'); return; } args.forEach((fileName) { open(cmd, fileName, (FileEntry fileEntry) { window.open(fileEntry.toUrl(), '$fileName'); }); }); } void open(String cmd, String path, successCallback) { cwd.getFile(path).then(successCallback, onError: (error) { if (error.code == FileError.NOT_FOUND_ERR) { writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(path)}: No such file or directory
    '); } else { errorHandler(error); } }); } void pwdCommand(String cmd, List args) { writeOutput(sanitizer.convert(cwd.fullPath)); } void rmCommand(String cmd, List args) { // Remove recursively? If so, remove the flag(s) from the arg list. var recursive = false; var switches = ['-r', '-f', '-rf', '-fr']; switches.forEach((sw) { var index = args.indexOf(sw); if (index != -1) { while (index != -1) { args.removeAt(index); index = args.indexOf(sw); } recursive = true; } }); args.forEach((fileName) { cwd.getFile(fileName).then((fileEntry) { fileEntry.remove().then((_) {}, onError: errorHandler); }, onError: (error) { if (recursive && error.code == FileError.TYPE_MISMATCH_ERR) { cwd.getDirectory(fileName) .then((DirectoryEntry dirEntry) => dirEntry.removeRecursively().then((_) {}, onError: errorHandler), onError: errorHandler); } else if (error.code == FileError.INVALID_STATE_ERR) { writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(fileName)}: is a directory
    '); } else { errorHandler(error); } }); }); } void rmdirCommand(String cmd, List args) { args.forEach((dirName) { cwd.getDirectory(dirName) .then((dirEntry) { dirEntry.remove().then((_) {}, onError: (error) { if (error.code == FileError.INVALID_MODIFICATION_ERR) { writeOutput('${sanitizer.convert(cmd)}: ${sanitizer.convert(dirName)}: Directory not empty
    '); } else { errorHandler(error); } }); }, onError: (error) => invalidOpForEntryType(error, cmd, dirName)); }); } void themeCommand(String cmd, List args) { var theme = args.join(' ').trim(); if (theme.isEmpty) { writeOutput('usage: ${sanitizer.convert(cmd)} ${sanitizer.convert(themes.toString())}'); } else { if (themes.contains(theme)) { setTheme(theme); } else { writeOutput('Error - Unrecognized theme used'); } } } void whoCommand(String cmd, List args) { writeOutput('${sanitizer.convert(document.title)}' ' - By: Eric Bidelman <ericbidelman@chromium.org>,' ' Adam Singer <financeCoding@gmail.com>'); } void writeOutput(String h) { output.insertAdjacentHtml('beforeEnd', h); } } ================================================ FILE: html5/web/file/terminal/terminal_filesystem.dart ================================================ // Copyright (c) 2012, 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 is a port of "Exploring the FileSystem APIs" to Dart. // See: http://www.html5rocks.com/en/tutorials/file/filesystem/ library terminal_filesystem; import 'dart:convert' show HtmlEscape; import 'dart:html'; part 'terminal.dart'; class TerminalFilesystem { Terminal term; void run() { term = new Terminal('#input-line', '#output', '#cmdline'); term.initializeFilesystem(false, 1024 * 1024); if (!window.location.hash.isEmpty) { var theme = window.location.hash.substring(1, window.location.hash.length).split('=')[1]; term.setTheme(theme); } else if (window.localStorage.containsKey('theme')) { term.setTheme(window.localStorage['theme']); } // Setup the DnD listeners for file drop. var body = document.body; body.onDragEnter.listen(onDragEnter); body.onDragOver.listen(onDragOver); body.onDrop.listen(onDrop); } void onDragEnter(MouseEvent event) { event.stopPropagation(); event.preventDefault(); Element dropTarget = event.target; dropTarget.classes.add('dropping'); } void onDragOver(MouseEvent event) { event.stopPropagation(); event.preventDefault(); // Explicitly show this is a copy. event.dataTransfer.dropEffect = 'copy'; } void onDrop(MouseEvent event) { event.stopPropagation(); event.preventDefault(); Element dropTarget = event.target; dropTarget.classes.remove('dropping'); term.addDroppedFiles(event.dataTransfer.files); term.writeOutput('
    File(s) added!
    '); } } void main() { new TerminalFilesystem().run(); } ================================================ FILE: html5/web/geolocation/trip_meter/README.md ================================================ ## Trip Meter: A Basic Geolocaton Example A port of the Geolocation example used in the [A Simple Trip Meter Using the Geolocation API] (http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/) article by Michael Mahemoff, originally published on HTML5Rocks. The Geolocation API lets you track a user's location. The API is device-agnostic; the underlying mechanism might be via GPS, wifi, or simply asking the user to enter their location manually. Since these lookups can take some time, the API is asynchronous, and you pass it a callback method whenever you request a location. The Trip Meter example display's the user's initial location, and it tracks the distance the user has travelled since the page was loaded. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/geolocation/trip_meter/index.html ================================================ TripMeter

    Starting Location (lat, lon):
    ???°, ???°

    Current Location (lat, lon):
    ???°, ???°

    Distance from starting location:
    0 km

    ================================================ FILE: html5/web/geolocation/trip_meter/trip_meter.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ #tripmeter { border: 3px double black; padding: 10px; margin: 10px 0; } p { color: #222; font: 14px Arial; } span { color: #00C; } ================================================ FILE: html5/web/geolocation/trip_meter/trip_meter.dart ================================================ // Copyright (c) 2012, 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 COPYING file. // This is a port of "A Simple Trip Meter Using the Geolocation API" to Dart. // See: http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/ import 'dart:html'; import 'dart:math'; // Reused code - copyright Moveable Type Scripts // http://www.movable-type.co.uk/scripts/latlong.html // Under Creative Commons License http://creativecommons.org/licenses/by/3.0/ num calculateDistance(num lat1, num lon1, num lat2, num lon2) { const EARTH_RADIUS = 6371; // km num latDiff = lat2 - lat1; num lonDiff = lon2 - lon1; // a is the square of half the chord length between the points. var a = pow(sin(latDiff / 2), 2) + cos(lat1) * cos (lat2) * pow(sin(lonDiff / 2), 2); var angularDistance = 2 * atan2(sqrt(a), sqrt(1 - a)); return EARTH_RADIUS * angularDistance; } // Don't use alert() in real code ;) void alertError(PositionError error) { window.alert("Error occurred. Error code: ${error.code}"); } void main(){ Geoposition startPosition; window.navigator.geolocation.getCurrentPosition() .then((Geoposition position) { startPosition = position; querySelector("#start-lat").text = "${startPosition.coords.latitude}"; querySelector("#start-lon").text = "${startPosition.coords.longitude}"; }, onError: (error) => alertError(error)); window.navigator.geolocation.watchPosition().listen((Geoposition position) { querySelector("#current-lat").text = "${position.coords.latitude}"; querySelector("#current-lon").text = "${position.coords.longitude}"; num distance = calculateDistance( startPosition.coords.latitude, startPosition.coords.longitude, position.coords.latitude, position.coords.longitude); querySelector("#distance").text = "$distance"; }, onError: (error) => alertError(error)); } ================================================ FILE: html5/web/indexeddb/todo/README.md ================================================ ## Simple Todo App using IndexedDB A port of the Todo example used in the [A Simple TODO list using HTML5 IndexedDB](http://www.html5rocks.com/en/tutorials/file/filesystem/) article by Paul Kinlan, originally published on HTML5Rocks. The example demonstrates how to create a very simple todo list manager using IndexedDB. IndexedDB is a data store that developers can use to store and manipulate data on the client side. IndexedDB is usually used as an Asynchronous API where the data is delivered to a defined callback function. You can open the example in Dart Editor and run it by clicking `index.html`. Or, you can try this [live demo](http://www.html5rocks.com/en/tutorials/indexeddb/todo/). Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/indexeddb/todo/index.html ================================================ A Simple ToDo List Using HTML5 IndexedDB
      ================================================ FILE: html5/web/indexeddb/todo/todo.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ body { color: #222; font: 14px Arial; } a { color: #3D5C9D; cursor: pointer; text-decoration: none; } li a { margin-left: 8px; } #todo { width: 200px; } ================================================ FILE: html5/web/indexeddb/todo/todo.dart ================================================ // Copyright (c) 2012, 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 COPYING file. // This is a port of "A Simple ToDo List Using HTML5 IndexedDB" to Dart. // See: http://www.html5rocks.com/en/tutorials/indexeddb/todo/ import 'dart:html'; import 'dart:indexed_db' as idb; import 'dart:async'; class TodoList { static final String _TODOS_DB = "todo"; static final String _TODOS_STORE = "todos"; idb.Database _db; int _version = 2; InputElement _input; Element _todoItems; TodoList() { _todoItems = querySelector('#todo-items'); _input = querySelector('#todo'); querySelector('input#submit').onClick.listen((e) => _onAddTodo()); } Future open() { return window.indexedDB.open(_TODOS_DB, version: _version, onUpgradeNeeded: _onUpgradeNeeded) .then(_onDbOpened) .catchError(_onError); } void _onError(e) { // Get the user's attention for the sake of this tutorial. (Of course we // would *never* use window.alert() in real life.) window.alert('Oh no! Something went wrong. See the console for details.'); window.console.log('An error occurred: {$e}'); } void _onDbOpened(idb.Database db) { _db = db; _getAllTodoItems(); } void _onUpgradeNeeded(idb.VersionChangeEvent e) { idb.Database db = (e.target as idb.OpenDBRequest).result; if (!db.objectStoreNames.contains(_TODOS_STORE)) { db.createObjectStore(_TODOS_STORE, keyPath: 'timeStamp'); } } void _onAddTodo() { var value = _input.value.trim(); if (value.length > 0) { _addTodo(value); } _input.value = ''; } Future _addTodo(String text) { var trans = _db.transaction(_TODOS_STORE, 'readwrite'); var store = trans.objectStore(_TODOS_STORE); return store.put({ 'text': text, 'timeStamp': new DateTime.now().millisecondsSinceEpoch.toString() }).then((_) => _getAllTodoItems()) .catchError((e) => _onError); } void _deleteTodo(String id) { var trans = _db.transaction(_TODOS_STORE, 'readwrite'); var store = trans.objectStore(_TODOS_STORE); var request = store.delete(id); request.then((e) => _getAllTodoItems(), onError: _onError); } void _getAllTodoItems() { _todoItems.nodes.clear(); var trans = _db.transaction(_TODOS_STORE, 'readwrite'); var store = trans.objectStore(_TODOS_STORE); // Get everything in the store. var request = store.openCursor(autoAdvance:true).listen((cursor) { _renderTodo(cursor.value); }, onError: _onError); } void _renderTodo(Map todoItem) { var textDisplay = new Element.tag('span'); textDisplay.text = todoItem['text']; var deleteControl = new Element.tag('a'); deleteControl.text = '[Delete]'; deleteControl.onClick.listen((e) => _deleteTodo(todoItem['timeStamp'])); var item = new Element.tag('li'); item.nodes.add(textDisplay); item.nodes.add(deleteControl); _todoItems.nodes.add(item); } } void main() { new TodoList().open(); } ================================================ FILE: html5/web/localstorage/basics/README.md ================================================ ## LocalStorage 101 A basic example showing the use of LocalStorage for persistence. LocalStorage is a simple key/value storage interface for Strings. Though widely supported, LocalStorage is a synchronous API. Because it involves I/O, this interface should not be used for high throughput operations. Consider IndexedDB as an alternative. For simple string keys and values, and as a replacement for cookies, LocalStorage is useful. When you enter a value in the username input in the example, it is stored in LocalStorage. The value is then retrieved from LocalStorage and displayed on the page. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/localstorage/basics/index.html ================================================ Local Storage in Dart

      Local Storage in Dart

      From local storage:

      ================================================ FILE: html5/web/localstorage/basics/localstorage.dart ================================================ // Copyright (c) 2012, 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. import 'dart:html'; void main() { InputElement username = querySelector('#username'); InputElement submit = querySelector('#save'); Element output = querySelector('#username-output'); Storage localStorage = window.localStorage; // Local storage is a Map, supporting string keys and values. String savedUsername = localStorage['username']; if (savedUsername != null) { output.text = savedUsername; } submit.onClick.listen((Event e) { output.text = username.value; localStorage['username'] = username.value; }); } ================================================ FILE: html5/web/pointerlock/fps/fps.css ================================================ /* Copyright (c) 2012, 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. */ body { background-color: #F8F8F8; font-family: 'Open Sans', sans-serif; font-size: 14px; font-weight: normal; line-height: 1.2em; margin: 15px; } p { color: #333; } #text { font-size: 24pt; text-align: center; margin-top: 140px; } ================================================ FILE: html5/web/pointerlock/fps/fps.dart ================================================ // Copyright (c) 2012, 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 is a port of "Pointer Lock And First Person Shooter Controls" to Dart. // See: http://www.html5rocks.com/en/tutorials/pointerlock/intro/ library fps; import 'dart:html'; import 'dart:web_gl'; import 'dart:typed_data'; import 'dart:math' as Math; import 'package:vector_math/vector_math.dart'; part 'fps_camera.dart'; part 'fps_controller.dart'; part 'quat.dart'; part 'opengl.dart'; FpsControllerView view; class FpsControllerView { final String elementId; CanvasElement canvas; Camera camera; MouseKeyboardCameraController controller; bool ownMouse; RenderingContext webGL; Shader vertexShader; Shader fragmentShader; Program shaderProgram; Buffer vertexBuffer; Float32List cameraTransform; int numVertices; double lastTime; /** * [elementId] The dom ID of the canvas element the view should render into */ FpsControllerView(this.elementId) { camera = new Camera(); controller = new MouseKeyboardCameraController(); canvas = querySelector(elementId); ownMouse = false; cameraTransform = new Float32List(16); } void _generateLine(List vertexBuffer, Vector3 b, Vector3 e, Vector4 color) { vertexBuffer.add(b.x); vertexBuffer.add(b.y); vertexBuffer.add(b.z); vertexBuffer.add(color.r); vertexBuffer.add(color.g); vertexBuffer.add(color.b); vertexBuffer.add(color.a); vertexBuffer.add(e.x); vertexBuffer.add(e.y); vertexBuffer.add(e.z); vertexBuffer.add(color.r); vertexBuffer.add(color.g); vertexBuffer.add(color.b); vertexBuffer.add(color.a); } void _generateLines(List vertexBuffer, Vector3 b, Vector3 e, Vector3 step, Vector4 color, int num) { Vector3 lineStart = new Vector3.copy(b); Vector3 lineEnd = new Vector3.copy(e); for (int i = 0; i < num; i++) { _generateLine(vertexBuffer, lineStart, lineEnd, color); lineStart.add(step); lineEnd.add(step); } } void _generateVertexBuffer() { vertexBuffer = webGL.createBuffer(); List vertexBufferData = new List(); var colors = { 'red': new Vector4(1.0, 0.0, 0.0, 1.0), 'green': new Vector4(0.0, 1.0, 0.0, 1.0), 'blue': new Vector4(0.0, 0.0, 1.0, 1.0) }; // Bottom Vector3 b = new Vector3(0.0, 0.0, -20.0); Vector3 e = new Vector3(0.0, 0.0, 0.0); Vector3 s = new Vector3(1.0, 0.0, 0.0); _generateLines(vertexBufferData, b, e, s, colors['green'], 21); b.setValues(0.0, 0.0, 0.0); e.setValues(20.0, 0.0, 0.0); s.setValues(0.0, 0.0, -1.0); _generateLines(vertexBufferData, b, e, s, colors['green'], 21); // Side b.setValues(20.0, 0.0, 0.0); e.setValues(20.0, 20.0, 0.0); s.setValues(0.0, 0.0, -1.0); _generateLines(vertexBufferData, b, e, s, colors['blue'], 21); b.setValues(20.0, 0.0, 0.0); e.setValues(20.0, 0.0, -20.0); s.setValues(0.0, 1.0, 0.0); _generateLines(vertexBufferData, b, e, s, colors['blue'], 21); // Side b.setValues(0.0, 0.0, -20.0); e.setValues(0.0, 20.0, -20.0); s.setValues(1.0, 0.0, 0.0); _generateLines(vertexBufferData, b, e, s, colors['red'], 21); b.setValues(0.0, 0.0, -20.0); e.setValues(20.0, 0.0, -20.0); s.setValues(0.0, 1.0, 0.0); _generateLines(vertexBufferData, b, e, s, colors['red'], 21); numVertices = vertexBufferData.length~/7; webGL.bindBuffer(RenderingContext.ARRAY_BUFFER, vertexBuffer); webGL.bufferDataTyped(RenderingContext.ARRAY_BUFFER, new Float32List.fromList(vertexBufferData), RenderingContext.STATIC_DRAW); } void initWebGL() { if (canvas == null) { throw new Exception('canvas not found $elementId can\'t be found'); } canvas.width = 640; canvas.height = 480; webGL = canvas.getContext("experimental-webgl"); if (webGL == null) { throw new Exception('WebGL is not supported'); } vertexShader = webGL.createShader(RenderingContext.VERTEX_SHADER); fragmentShader = webGL.createShader(RenderingContext.FRAGMENT_SHADER); shaderProgram = webGL.createProgram(); webGL.shaderSource(vertexShader, ''' precision highp float; attribute vec3 vPosition; attribute vec4 vColor; uniform mat4 cameraTransform; varying vec4 fColor; void main() { fColor = vColor; vec4 vPosition4 = vec4(vPosition.x, vPosition.y, vPosition.z, 1.0); gl_Position = cameraTransform*vPosition4; } '''); webGL.shaderSource(fragmentShader, ''' precision mediump float; varying vec4 fColor; void main() { gl_FragColor = fColor; } '''); webGL.compileShader(vertexShader); webGL.compileShader(fragmentShader); webGL.attachShader(shaderProgram, vertexShader); webGL.attachShader(shaderProgram, fragmentShader); webGL.linkProgram(shaderProgram); _generateVertexBuffer(); } void clicked(Event event) { canvas.requestPointerLock(); } /* Returns true if the pointer is owned by our canvas element */ bool get _pointerLocked => canvas == document.pointerLockElement; void pointerLockChange(Event event) { // Check if we own the mouse. ownMouse = _pointerLocked; } static const keyCodeA = 65; static const keyCodeD = 68; static const keyCodeS = 83; static const keyCodeW = 87; void keydown(KeyboardEvent event) { if (!ownMouse) { // We don't respond to keyboard commands if we don't own the mouse return; } switch (event.keyCode) { case keyCodeW: controller.forward = true; break; case keyCodeA: controller.strafeLeft = true; break; case keyCodeD: controller.strafeRight = true; break; case keyCodeS: controller.backward = true; break; } } void keyup(KeyboardEvent event) { if (!ownMouse) { // We don't respond to keyboard commands if we don't own the mouse return; } switch (event.keyCode) { case keyCodeW: controller.forward = false; break; case keyCodeA: controller.strafeLeft = false; break; case keyCodeD: controller.strafeRight = false; break; case keyCodeS: controller.backward = false; break; } } void mouseMove(MouseEvent event) { if (!ownMouse) { // We don't rotate the view if we don't own the mouse return; } controller.accumDX += event.movement.x; controller.accumDY += event.movement.y; } // Subscribe to input events void bind() { document.onPointerLockChange.listen(pointerLockChange); canvas.onClick.listen(clicked); document.onKeyDown.listen(keydown); document.onKeyUp.listen(keyup); document.onMouseMove.listen(mouseMove); } void update(double time) { if (lastTime == null) { // This skips the first frame but gives us an origin in time. lastTime = time; return; } var dt = (time - lastTime) / 1000.0; lastTime = time; controller.updateCamera(dt, camera); } void draw() { webGL.viewport(0, 0, canvas.width, canvas.height); webGL.clearColor(0.0, 0.0, 0.0, 1.0); webGL.clearDepth(1.0); webGL.clear(RenderingContext.COLOR_BUFFER_BIT | RenderingContext.DEPTH_BUFFER_BIT); webGL.disable(RenderingContext.DEPTH_TEST); webGL.enableVertexAttribArray(0); webGL.enableVertexAttribArray(1); webGL.bindBuffer(RenderingContext.ARRAY_BUFFER, vertexBuffer); webGL.vertexAttribPointer(0, 4, RenderingContext.FLOAT, false, 28, 12); webGL.bindBuffer(RenderingContext.ARRAY_BUFFER, vertexBuffer); webGL.vertexAttribPointer(1, 3, RenderingContext.FLOAT, false, 28, 0); webGL.useProgram(shaderProgram); var cameraTransformUniformIndex = webGL.getUniformLocation(shaderProgram, 'cameraTransform'); Matrix4 view = camera.lookAtMatrix; Matrix4 projection = camera.projectionMatrix; Matrix4 projectionView = projection * view; projectionView.copyIntoArray(cameraTransform, 0); webGL.uniformMatrix4fv(cameraTransformUniformIndex, false, cameraTransform); webGL.drawArrays(RenderingContext.LINES, 0, numVertices); webGL.flush(); } } void animate(double time) { view.update(time); view.draw(); window.requestAnimationFrame(animate); } void main() { view = new FpsControllerView('#webGLCanvas'); view.initWebGL(); view.bind(); window.requestAnimationFrame(animate); } ================================================ FILE: html5/web/pointerlock/fps/fps_camera.dart ================================================ // Copyright (c) 2012, 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. part of fps; class Camera { Vector3 eyePosition; Vector3 upDirection; Vector3 lookAtPosition; num zNear; num zFar; num aspectRatio; num fOV; Camera() { eyePosition = new Vector3(0.0, 2.0, 0.0); lookAtPosition = new Vector3(1.0, 2.0, -1.0); upDirection = new Vector3(0.0, 1.0, 0.0); fOV = 0.785398163; // 90 degrees zNear = 1.0; zFar = 1000.0; aspectRatio = 1.7777778; } String toString() { return '$eyePosition -> $lookAtPosition'; } num get yaw { Vector3 z = new Vector3(0.0, 0.0, 1.0); Vector3 forward = frontDirection; forward.normalize(); return degrees(Math.acos(forward.dot(z))); } num get pitch { Vector3 y = new Vector3(0.0, 1.0, 0.0); Vector3 forward = frontDirection; forward.normalize(); return degrees(Math.acos(forward.dot(y))); } Matrix4 get projectionMatrix { return makePerspective(fOV, aspectRatio, zNear, zFar); } Matrix4 get lookAtMatrix { return makeLookAt(eyePosition, lookAtPosition, upDirection); } void copyProjectionMatrixIntoArray(Float32List pm) { Matrix4 m = makePerspective(fOV, aspectRatio, zNear, zFar); m.copyIntoArray(pm); } void copyViewMatrixIntoArray(Float32List vm) { Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); m.copyIntoArray(vm); } void copyNormalMatrixIntoArray(Float32List nm) { Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); m.copyIntoArray(nm); } void copyProjectionMatrix(Matrix4 pm) { Matrix4 m = makePerspective(fOV, aspectRatio, zNear, zFar); m.copyInto(pm); } void copyViewMatrix(Matrix4 vm) { Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); m.copyInto(vm); } void copyNormalMatrix(Matrix4 nm) { Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); m.copyInto(nm); } void copyEyePosition(Vector3 ep) { eyePosition.copyInto(ep); } void copyLookAtPosition(Vector3 lap) { lookAtPosition.copyInto(lap); } Vector3 get frontDirection => lookAtPosition - eyePosition; } ================================================ FILE: html5/web/pointerlock/fps/fps_controller.dart ================================================ // Copyright (c) 2012, 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. part of fps; class MouseKeyboardCameraController { bool up = false; bool down = false; bool strafeLeft = false; bool strafeRight = false; bool forward = false; bool backward = false; num floatVelocity = 5.0; num strafeVelocity = 5.0; num forwardVelocity = 5.0; num mouseSensitivity = 360.0; int accumDX = 0; int accumDY = 0; MouseKeyboardCameraController(); void updateCamera(num seconds, Camera cam) { _moveFloat(seconds, up, down, cam); _moveStrafe(seconds, strafeRight, strafeLeft, cam); _moveForward(seconds, forward, backward, cam); _rotateView(seconds, cam); } num _velocityScale(bool positive, bool negative) { num scale = 0.0; if (positive) { scale += 1.0; } if (negative) { scale -= 1.0; } return scale; } void _moveFloat(num dt, bool positive, bool negative, Camera cam) { var scale = _velocityScale(positive, negative); if (scale == 0.0) { return; } scale = scale * dt * floatVelocity; Vector3 upDirection = new Vector3(0.0, 1.0, 0.0); upDirection.scale(scale); cam.lookAtPosition.add(upDirection); cam.eyePosition.add(upDirection); } void _moveStrafe(num dt, bool positive, bool negative, Camera cam) { var scale = _velocityScale(positive, negative); if (scale == 0.0) { return; } scale = scale * dt * strafeVelocity; Vector3 frontDirection = cam.frontDirection; frontDirection.normalize(); Vector3 upDirection = new Vector3(0.0, 1.0, 0.0); Vector3 strafeDirection = frontDirection.cross(upDirection); strafeDirection.scale(scale); cam.lookAtPosition.add(strafeDirection); cam.eyePosition.add(strafeDirection); } void _moveForward(num dt, bool positive, bool negative, Camera cam) { var scale = _velocityScale(positive, negative); if (scale == 0.0) { return; } scale = scale * dt * forwardVelocity; Vector3 frontDirection = cam.frontDirection; frontDirection.normalize(); frontDirection.scale(scale); cam.lookAtPosition.add(frontDirection); cam.eyePosition.add(frontDirection); } void _rotateView(num dt, Camera cam) { Vector3 frontDirection = cam.frontDirection; frontDirection.normalize(); Vector3 upDirection = new Vector3(0.0, 1.0, 0.0); Vector3 strafeDirection = frontDirection.cross(upDirection); strafeDirection.normalize(); num mouseYawDelta = accumDX / mouseSensitivity; num mousePitchDelta = accumDY / mouseSensitivity; accumDX = 0; accumDY = 0; // Pitch rotation bool above = false; if (frontDirection.y > 0.0) { above = true; } num fDotUp = frontDirection.dot(upDirection); num pitchAngle = Math.acos(fDotUp); num pitchDegrees = degrees(pitchAngle); const minPitchAngle = 0.785398163; const maxPitchAngle = 2.35619449; num minPitchDegrees = degrees(minPitchAngle); num maxPitchDegrees = degrees(maxPitchAngle); _rotateEyeAndLook(mousePitchDelta, strafeDirection, cam); _rotateEyeAndLook(mouseYawDelta, upDirection, cam); } void _rotateEyeAndLook(num delta_angle, Vector3 axis, Camera cam) { quat q = new quat(axis, delta_angle); Vector3 frontDirection = cam.frontDirection; frontDirection.normalize(); q.rotate(frontDirection); frontDirection.normalize(); cam.lookAtPosition = cam.eyePosition + frontDirection; } } ================================================ FILE: html5/web/pointerlock/fps/index.html ================================================ Pointer Lock First Person Shooter Controls

      Click on view to active

      Keys: W,A,S,D - Move forward, left, backward, and right respectively

      Mouse: Rotates view

      ================================================ FILE: html5/web/pointerlock/fps/opengl.dart ================================================ /* Copyright (C) 2013 John McCutchan This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ part of fps; /** * Returns an OpenGL look at matrix. * The camera is located at [cameraPosition] and is focused * on [cameraFocusPostion]. * * The [upDirection] is almost always (0, 1, 0). */ Matrix4 makeLookAt(Vector3 cameraPosition, Vector3 cameraFocusPosition, Vector3 upDirection) { Vector3 z = cameraPosition - cameraFocusPosition; z.normalize(); Vector3 x = upDirection.cross(z); x.normalize(); Vector3 y = z.cross(x); y.normalize(); Matrix4 r = new Matrix4.zero(); r.row0 = new Vector4(x.x, x.y, x.z, 0.0); r.row1 = new Vector4(y.x, y.y, y.z, 0.0); r.row2 = new Vector4(z.x, z.y, z.z, 0.0); r.row3 = new Vector4(1.0, 1.0, 1.0, 1.0); r = r.transposed(); Vector3 rotatedEye = r * -cameraPosition; r.row3 = new Vector4(rotatedEye.x, rotatedEye.y, rotatedEye.z, 0.0); return r; } /** * Returns an OpenGL perspective camera projection matrix * */ Matrix4 makePerspective(double fov_y_radians, double aspect_ratio, double znear, double zfar) { double height = Math.tan(fov_y_radians * 0.5) * znear; double width = height * aspect_ratio; return makeFrustum(-width, width, -height, height, znear, zfar); } /** * Returns an OpenGL frustum camera projection matrix */ Matrix4 makeFrustum(num left, num right, num bottom, num top, num near, num far) { double two_near = 2.0 * near; double right_minus_left = right - left; double top_minus_bottom = top - bottom; double far_minus_near = far - near; Matrix4 view = new Matrix4.zero(); //view[0].x = two_near / right_minus_left; view.row0 = new Vector4(two_near / right_minus_left, 0.0, 0.0, 0.0); // view[1].y = two_near / top_minus_bottom; view.row1 = new Vector4(0.0, two_near / top_minus_bottom, 0.0, 0.0); // view[2].x = (right + left) / right_minus_left; // view[2].y = (top + bottom) / top_minus_bottom; // view[2].z = -(far + near) / far_minus_near; // view[2].w = -1.0; Vector4 row2 = new Vector4((right + left) / right_minus_left, (top + bottom) / top_minus_bottom, -(far + near) / far_minus_near, -1.0); view.row2 = row2; // view[3].z = -(two_near * far) / far_minus_near; // view[3].w = 0.0; Vector4 row3 = new Vector4(0.0, 0.0, -(two_near * far) / far_minus_near, 0.0); view.row3 = row3; return view; } /** * Returns an OpenGL orthographic camera projection matrix */ Matrix4 makeOrthographic(double left, double right, double bottom, double top, double znear, double zfar) { double rml = right - left; double rpl = right + left; double tmb = top - bottom; double tpb = top + bottom; double fmn = zfar - znear; double fpn = zfar + znear; Matrix4 r = new Matrix4.zero(); // r[0].x = 2.0/rml; r.row0 = new Vector4(2.0/rml, 0.0, 0.0, 0.0); // r[1].y = 2.0/tmb; r.row1 = new Vector4(0.0, 2.0/tmb, 0.0, 0.0); // r[2].z = -2.0/fmn; r.row2 = new Vector4(0.0, 0.0, -2.0/fmn, 0.0); // r[3].x = -rpl/rml; // r[3].y = -tpb/tmb; // r[3].z = -fpn/fmn; // r[3].w = 1.0; r.row3 = new Vector4(-rpl/rml, -tpb/tmb, -fpn/fmn, 1.0); return r; } /** * Returns a transformation matrix that transforms points onto * the plane specified with [planeNormal] and [planePoint] */ Matrix4 makePlaneProjection(Vector3 planeNormal, Vector3 planePoint) { Vector4 v = new Vector4(planeNormal.x, planeNormal.y, planeNormal.z, 0.0); Matrix4 outer = new Matrix4.outer(v, v); Matrix4 r = new Matrix4.zero(); r = r - outer; //Vector3 scaledNormal = (planeNormal.scaled(dot(planePoint, planeNormal))); double d = planePoint.dot(planeNormal); Vector3 scaledNormal = planeNormal.scaled(d); Vector4 T = new Vector4(scaledNormal.x, scaledNormal.y, scaledNormal.z, 1.0); r.setColumn(3, T); return r; } /** * Returns a transformation matrix that transforms points by reflecting * them through the plane specified with [planeNormal] and [planePoint] */ Matrix4 makePlaneReflection(Vector3 planeNormal, Vector3 planePoint) { Vector4 v = new Vector4(planeNormal.x, planeNormal.y, planeNormal.z, 0.0); Matrix4 outer = new Matrix4.outer(v,v); outer.scale(2.0); Matrix4 r = new Matrix4.zero(); r = r - outer; // double scale = 2.0 * dot(planePoint, planeNormal); double scale = 2.0 * planePoint.dot(planeNormal); Vector3 scaledNormal = (planeNormal.scaled(scale)); Vector4 T = new Vector4(scaledNormal.x, scaledNormal.y, scaledNormal.z, 1.0); r.setColumn(3, T); return r; } /** * On success, Sets [pickWorld] to be the world space position of * the screen space [pickX], [pickY], and [pickZ]. * * The viewport is specified by ([viewportX], [viewportWidth]) and * ([viewportY], [viewportHeight]). * * [cameraMatrix] includes both the projection and view transforms. * * [pickZ] is typically either 0.0 (near plane) or 1.0 (far plane). * * Returns false on error, for example, the mouse is not in the viewport * */ bool unproject(Matrix4 cameraMatrix, num viewportX, num viewportWidth, num viewportY, num viewportHeight, num pickX, num pickY, num pickZ, Vector3 pickWorld) { pickX = (pickX - viewportX); pickY = (pickY - viewportY); pickX = (2.0 * pickX / viewportWidth) - 1.0; pickY = (2.0 * pickY / viewportHeight) - 1.0; pickZ = (2.0 * pickZ) - 1.0; // Check if pick point is inside unit cube if (pickX < -1.0 || pickY < -1.0 || pickX > 1.0 || pickY > 1.0 || pickZ < -1.0 || pickZ > 1.0) { return false; } // Copy camera matrix. Matrix4 invertedCameraMatrix = new Matrix4.copy(cameraMatrix); // Invert the camera matrix. invertedCameraMatrix.invert(); // Determine intersection point. Vector4 v = new Vector4(pickX, pickY, pickZ, 1.0); invertedCameraMatrix.transform(v); if (v.w == 0.0) { return false; } double invW = 1.0 / v.w; pickWorld.x = v.x * invW; pickWorld.y = v.y * invW; pickWorld.z = v.z * invW; return true; } /** * On success, [rayNear] and [rayFar] are the points where * the screen space [pickX], [pickY] intersect with the near and far * planes respectively. * * The viewport is specified by ([viewportX], [viewportWidth]) and * ([viewportY], [viewportHeight]). * * [cameraMatrix] includes both the projection and view transforms. * * Returns false on error, for example, the mouse is not in the viewport * */ bool pickRay(Matrix4 cameraMatrix, num viewportX, num viewportWidth, num viewportY, num viewportHeight, num pickX, num pickY, Vector3 rayNear, Vector3 rayFar) { bool r; r = unproject(cameraMatrix, viewportX, viewportWidth, viewportY, viewportHeight, pickX, viewportHeight-pickY, 0.0, rayNear); if (!r) { return false; } r = unproject(cameraMatrix, viewportX, viewportWidth, viewportY, viewportHeight, pickX, viewportHeight-pickY, 1.0, rayFar); return r; } ================================================ FILE: html5/web/pointerlock/fps/quat.dart ================================================ /* Copyright (C) 2013 John McCutchan This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ part of fps; class quat { double x; double y; double z; double w; /// Constructs a quaternion using the raw values [x], [y], [z], and [w] quat.raw(this.x, this.y, this.z, this.w); /** * Constructs a new quaternion. Behaviour depends on the types of arguments: * * + *([double] x,[double] y,[double] z,[double] w)* Raw values * + *([vec3] axis,[double] angle)* Rotation of [angle] degrees around [axis] * + *([quat] other)* Copy of other * + *([mat3])* Convert rotation matrix into quaternion * * */ quat([dynamic a, dynamic b, dynamic c, dynamic d]) { x = 0.0; y = 0.0; z = 0.0; w = 1.0; if (a is double && b is double && c is double && d is double) { x = a; y = b; z = c; w = d; return; } if (a is Vector3 && b is double) { setAxisAngle(a, b); return; } if (a is Vector3) { x = a.x; y = a.y; z = a.z; w = 0.0; return; } if (a is quat) { x = a.x; y = a.y; z = a.z; w = a.w; return; } if (a is Matrix3) { double trace = (a as Matrix3).trace(); if (trace > 0.0) { double s = Math.sqrt(trace + 1.0); w = s * 0.5; s = 0.5 / s; x = (a.col1.z - a.col2.y) * s; y = (a.col2.x - a.col0.z) * s; z = (a.col0.y - a.col1.x) * s; } else { int i = a.col0.x < a.col1.y ? (a.col1.y < a.col2.z ? 2 : 1) : (a.col0.x < a.col2.z ? 2 : 0); int j = (i + 1) % 3; int k = (i + 2) % 3; double s = Math.sqrt(a[i][i] - a[j][j] - a[k][k] + 1.0); this[i] = s * 0.5; s = 0.5 / s; this[3] = (a[j][k] - a[k][j]) * s; this[j] = (a[i][j] + a[j][i]) * s; this[k] = (a[i][k] + a[k][i]) * s; } } } /// Constructs a new quaternion representing a rotation of [angle] around [axis] quat.axisAngle(Vector3 axis, double angle) { setAxisAngle(axis, angle); } /// Constructs a new quaternion which is a copy of [original] quat.copy(quat original) { x = original.x; y = original.y; z = original.z; w = original.w; } /** Constructs a random rotation */ quat.random(Math.Random rn) { // From: "Uniform Random Rotations", Ken Shoemake, Graphics Gems III, // pg. 124-132 double x0 = rn.nextDouble(); double r1 = Math.sqrt(1.0 - x0); double r2 = Math.sqrt(x0); double t1 = Math.PI*2.0 * rn.nextDouble(); double t2 = Math.PI*2.0 * rn.nextDouble(); double c1 = Math.cos(t1); double s1 = Math.sin(t1); double c2 = Math.cos(t2); double s2 = Math.sin(t2); x = s1 * r1; y = c1 * r1; z = s2 * r2; w = c2 * r2; } /// Constructs the identity quaternion quat.identity() { x = 0.0; y = 0.0; z = 0.0; w = 1.0; } /** Constructs the time derivative of [q] with angular velocity [omega] */ quat.dq(quat q, Vector3 omega) { x = omega.x * q.w + omega.y * q.z - omega.z * q.y; y = omega.y * q.w + omega.z * q.x - omega.x * q.z; z = omega.z * q.w + omega.x * q.y - omega.y * q.x; w = -omega.x * q.x - omega.y * q.y - omega.z * q.z; x *= 0.5; y *= 0.5; z *= 0.5; w *= 0.5; } /// Returns a new copy of this quat clone() { return new quat.copy(this); } /// Copy [source] into [this] void copyFrom(quat source) { x = source.x; y = source.y; z = source.z; w = source.w; } /// Copy [this] into [target] void copyTo(quat target) { target.x = x; target.y = y; target.z = z; target.w = w; } /** Set quaternion with rotation of [radians] around [axis] */ void setAxisAngle(Vector3 axis, double radians) { double len = axis.length; if (len == 0.0) { return; } double halfSin = Math.sin(radians * 0.5) / len; x = axis.x * halfSin; y = axis.y * halfSin; z = axis.z * halfSin; w = Math.cos(radians * 0.5); } /** Set quaternion with rotation of [yaw], [pitch] and [roll] */ void setEuler(double yaw, double pitch, double roll) { double halfYaw = yaw * 0.5; double halfPitch = pitch * 0.5; double halfRoll = roll * 0.5; double cosYaw = Math.cos(halfYaw); double sinYaw = Math.sin(halfYaw); double cosPitch = Math.cos(halfPitch); double sinPitch = Math.sin(halfPitch); double cosRoll = Math.cos(halfRoll); double sinRoll = Math.sin(halfRoll); x = cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw; y = cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw; z = sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw; w = cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw; } /** Normalize [this] */ quat normalize() { double l = length; if (l == 0.0) { return this; } x /= l; y /= l; z /= l; w /= l; return this; } /** Conjugate [this] */ quat conjugate() { x = -x; y = -y; z = -z; w = w; return this; } /** Invert [this] */ quat inverse() { double l = 1.0 / length2; x = -x * l; y = -y * l; z = -z * l; w = w * l; return this; } /** Normalized copy of [this]. Optionally stored in [out]*/ quat normalized([quat out=null]) { if (out == null) { out = new quat.copy(this); } return out.normalize(); } /** Conjugated copy of [this]. Optionally stored in [out] */ quat conjugated([quat out=null]) { if (out == null) { out = new quat.copy(this); } return out.conjugate(); } /** Inverted copy of [this]. Optionally stored in [out] */ quat inverted([quat out=null]) { if (out == null) { out = new quat.copy(this); } return out.inverse(); } /** Radians of rotation */ double get radians { return 2.0 * Math.acos(w); } /** Axis of rotation */ Vector3 get axis { double divisor = 1.0 - (w*w); return new Vector3(x / divisor, y / divisor, z / divisor); } /** Squared length */ double get length2 { return (x*x) + (y*y) + (z*z) + (w*w); } /** Length */ double get length { return Math.sqrt(length2); } /** Returns a copy of [v] rotated by quaternion. Copy optionally stored in [out] */ Vector3 rotated(Vector3 v, [Vector3 out=null]) { if (out == null) { out = new Vector3.copy(v); } else { out.setFrom(v); } return rotate(out); } /** Rotates [v] by [this]. Returns [v]. */ Vector3 rotate(Vector3 v) { // conjugate(this) * [v,0] * this double tix = -x; double tiy = -y; double tiz = -z; double tiw = w; double tx = tiw * v.x + tix * 0.0 + tiy * v.z - tiz * v.y; double ty = tiw * v.y + tiy * 0.0 + tiz * v.x - tix * v.z; double tz = tiw * v.z + tiz * 0.0 + tix * v.y - tiy * v.x; double tw = tiw * 0.0 - tix * v.x - tiy * v.y - tiz * v.z; double result_x = tw * x + tx * w + ty * z - tz * y; double result_y = tw * y + ty * w + tz * x - tx * z; double result_z = tw * z + tz * w + tx * y - ty * x; v.x = result_x; v.y = result_y; v.z = result_z; return v; } /** Return a copy of [this] divided by [scale] */ quat operator/(double scale) { return new quat(x / scale, y / scale, z / scale, w / scale); } /** Returns copy of [this] multiplied by [scale] * Returns copy of [this] rotated by [otherQuat] */ quat operator*(dynamic other) { if (other is double) { return new quat(x * other, y * other, z * other, w * other); } if (other is quat) { return new quat(w * other.x + x * other.w + y * other.z - z * other.y, w * other.y + y * other.w + z * other.x - x * other.z, w * other.z + z * other.w + x * other.y - y * other.x, w * other.w - x * other.x - y * other.y - z * other.z); } } /** Returns copy of [this] - [other] */ quat operator+(quat other) { return new quat(x + other.x, y + other.y, z + other.z, w + other.w); } /** Returns copy of [this] + [other] */ quat operator-(quat other) { return new quat(x - other.x, y - other.y, z - other.z, w - other.w); } /** Returns negated copy of [this] */ quat operator-() { return new quat(-x, -y, -z, -w); } /** Treats [this] as an array and returns [x],[y],[z], or [w] */ double operator[](int i) { assert(i >= 0 && i < 4); switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; } return 0.0; } /** Treats [this] as an array and assigns [x],[y],[z], or [w] the value of [arg]*/ void operator[]=(int i, double arg) { assert(i >= 0 && i < 4); switch (i) { case 0: x = arg; break; case 1: y = arg; break; case 2: z = arg; break; case 3: w = arg; break; } } /** Returns a rotation matrix containing the same rotation as [this] */ Matrix3 asRotationMatrix() { double d = length2; assert(d != 0.0); double s = 2.0 / d; double xs = x * s; double ys = y * s; double zs = z * s; double wx = w * xs; double wy = w * ys; double wz = w * zs; double xx = x * xs; double xy = x * ys; double xz = x * zs; double yy = y * ys; double yz = y * zs; double zz = z * zs; return new Matrix3(1.0 - (yy + zz), xy + wz, xz - wy, // column 0 xy - wz, 1.0 - (xx + zz), yz + wx, // column 1 xz + wy, yz - wx, 1.0 - (xx + yy) // column 2 ); } /** Returns a printable string */ String toString() { return '$x, $y, $z @ $w'; } /** Returns relative error between [this] and [correct] */ double relativeError(quat correct) { quat diff = correct - this; double norm_diff = diff.length; double correct_norm = correct.length; return norm_diff/correct_norm; } /** Returns absolute error between [this] and [correct] */ double absoluteError(quat correct) { double this_norm = length; double correct_norm = correct.length; double norm_diff = (this_norm - correct_norm).abs(); return norm_diff; } } ================================================ FILE: html5/web/speed/animations/README.md ================================================ ## Working with RequestAnimationFrame A port of the example used in the [Leaner, Meaner, Faster Animations with requestAnimationFrame](http://www.html5rocks.com/en/tutorials/speed/animations/) article by Paul Lewis, originally published on HTML5Rocks. The article explains how to correctly use requestAnimationFrame for your animations. Here is a summary of the article contents: * Decouple your events from animations * Avoid animations that result in reflow-repaint loops * Update your RAF calls to expect a high resolution timestamp as the first parameter * Only call RAF when you have visual updates to do Use the up and down keys to activate the animation. The up key moves the circles from right to left, and the down key moves them from left to right. Please report any [bugs or feature requests](http://dartbug.com/new). ================================================ FILE: html5/web/speed/animations/animations.css ================================================ /* Copyright (c) 2012, 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 COPYING file. */ .mover { position: absolute; width: 100px; height: 100px; background: url(http://1-ps.googleusercontent.com/x/s.html5rocks-hrd.appspot.com/www.html5rocks.com/en/tutorials/speed/animations/particle.png.pagespeed.ce.jWkhaHzlBa.png) center no-repeat; left: 90%; -webkit-transition: left 1.3s ease-out; -moz-transition: left 1.3s ease-out; -ms-transition: left 1.3s ease-out; -o-transition: left 1.3s ease-out; transition: left 1.3s ease-out; } .mover.left { left: 10%; } ================================================ FILE: html5/web/speed/animations/animations.dart ================================================ // Copyright (c) 2012, 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 is a port of "Leaner, Meaner, Faster Animations with // requestAnimationFrame" to Dart. // See: http://www.html5rocks.com/en/tutorials/speed/animations/ import 'dart:html'; class AnimationExample { final _numMovers = 500; List _movers; List _moverTops; num _lastScrollY = 0; bool _ticking = false; AnimationExample() { _movers = new List(_numMovers); _moverTops = new List(_numMovers); for (var i = 0; i < _numMovers; i++) { var mover = new Element.tag("div"); mover.classes.add("mover"); mover.style.top = "${i * 10}px"; document.body.nodes.add(mover); _movers[i] = mover; } window.onScroll.listen((e) => _onScroll()); } void _onScroll() { _lastScrollY = window.scrollY; _requestTick(); } void _requestTick() { if (!_ticking) { window.requestAnimationFrame(_update); _ticking = true; } } void _update(num time) { var halfWindowHeight = window.innerHeight * 0.5; var offset = 0; for (var i = 0; i < _movers.length; i++) { Element mover = _movers[i]; _moverTops[i] = mover.offsetTop; } // Using separate for loops is a subtle browser optimization. See the // tutorial. for (var i = 0; i < _movers.length; i++) { Element mover = _movers[i]; if (_lastScrollY > _moverTops[i] - halfWindowHeight) { mover.classes.add('left'); } else { mover.classes.remove('left'); } } _ticking = false; } } void main() { new AnimationExample(); } ================================================ FILE: html5/web/speed/animations/index.html ================================================ Animations ================================================ FILE: html5/web/video/basics/README.md ================================================ ## HTML5 Video A port of an example used in the [HTML5 Video](http://www.html5rocks.com/en/tutorials/video/basics/) article by Ernest Delgado, originally published on HTML5Rocks. The example shows how to use the `