├── .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.lock ├── pubspec.yaml └── runtests.sh ├── deferred_loading_samples ├── README.md ├── deferred_loading_example │ ├── README.md │ ├── bin │ │ └── main.dart │ ├── lib │ │ └── hello.dart │ ├── pubspec.lock │ └── pubspec.yaml └── lazyloader │ ├── README.md │ ├── lib │ ├── breakfast.dart │ ├── dinner.dart │ └── lunch.dart │ ├── pubspec.lock │ ├── pubspec.yaml │ └── web │ ├── index.html │ ├── main.dart │ └── styles.css ├── html5 ├── .pub │ └── bin │ │ └── sdk-version ├── AUTHORS ├── README.md ├── pubspec.lock ├── 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 │ │ └── images │ │ │ └── html5rocks.png │ └── imagefilters │ │ ├── README.md │ │ ├── imagefilters.css │ │ ├── imagefilters.dart │ │ ├── images │ │ └── demo_small.png │ │ └── 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.mp3 │ │ ├── example.ogg │ │ └── example.wav │ ├── 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 │ │ ├── photo.jpg │ │ └── 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 │ │ │ └── textures │ │ │ ├── earth_diffuse.jpg │ │ │ ├── jupiter_diffuse.jpg │ │ │ ├── mars_diffuse.jpg │ │ │ ├── mercury_diffuse.jpg │ │ │ ├── moon_diffuse.jpg │ │ │ ├── negativeX.jpg │ │ │ ├── negativeY.jpg │ │ │ ├── negativeZ.jpg │ │ │ ├── neptune_diffuse.jpg │ │ │ ├── positiveX.jpg │ │ │ ├── positiveY.jpg │ │ │ ├── positiveZ.jpg │ │ │ ├── saturn_diffuse.jpg │ │ │ ├── sun_diffuse.jpg │ │ │ ├── uranus_diffuse.jpg │ │ │ └── venus_diffuse.jpg │ └── utils │ │ └── webgl_utils.dart │ └── websockets │ └── basics │ ├── README.md │ ├── index.html │ └── websocket_sample.dart └── polymer_mini_samples ├── README.md ├── pubspec.lock ├── 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 /.gitignore: -------------------------------------------------------------------------------- 1 | # JetBrains 2 | .idea/ 3 | # Dart Editor 4 | *.dart.js 5 | *.dart.js.map 6 | *.dart.js.deps 7 | 8 | # pub 9 | .pub 10 | packages 11 | .packages 12 | build 13 | 14 | #other 15 | .settings 16 | .buildlog 17 | .DS_Store 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2012, the Dart project authors. All rights reserved. 2 | Redistribution and use in source and binary forms, with or without 3 | modification, are permitted provided that the following conditions are 4 | met: 5 | * Redistributions of source code must retain the above copyright 6 | notice, this list of conditions and the following disclaimer. 7 | * Redistributions in binary form must reproduce the above 8 | copyright notice, this list of conditions and the following 9 | disclaimer in the documentation and/or other materials provided 10 | with the distribution. 11 | * Neither the name of Google Inc. nor the names of its 12 | contributors may be used to endorse or promote products derived 13 | from this software without specific prior written permission. 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 15 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 16 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 17 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 18 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 19 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 20 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 24 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 | 26 | ====================================================================== 27 | 28 | Portions of these code samples were derived from tutorials or samples 29 | on http://www.html5rocks.com. These portions are licensed as follows: 30 | 31 | Copyright 2012 - Google, Inc. 32 | 33 | Licensed under the Apache License, Version 2.0 (the "License"); 34 | you may not use this file except in compliance with the License. 35 | You may obtain a copy of the License at 36 | 37 | http://www.apache.org/licenses/LICENSE-2.0 38 | 39 | Unless required by applicable law or agreed to in writing, software 40 | distributed under the License is distributed on an "AS IS" BASIS, 41 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 42 | See the License for the specific language governing permissions and 43 | limitations under the License. 44 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DEPRECATED 2 | 3 | This repo is deprecated; please use the new samples repo: https://github.com/dart-lang/samples 4 | 5 | ## Contents 6 | * [HTML5 samples](html5/README.md) 7 | * [Dart I/O mini samples](dart_io_mini_samples/README.md) 8 | * [Dart deferred loading samples](deferred_loading_samples/README.md) 9 | 10 | Note: The Angulardart examples have been moved to 11 | [https://github.com/shailen/angulardart-samples](https://github.com/shailen/angulardart-samples). 12 | 13 | -------------------------------------------------------------------------------- /dart_io_mini_samples/AUTHORS: -------------------------------------------------------------------------------- 1 | Mary Campione 2 | Patrice Chalin 3 | Shailen Tuli 4 | Günter Zöchbauer 5 | 6 | -------------------------------------------------------------------------------- /dart_io_mini_samples/LICENSE: -------------------------------------------------------------------------------- 1 | Except as otherwise noted, the content of this page is licensed under the 2 | Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States 3 | License [1], and code samples are licensed 4 | under the BSD License: 5 | 6 | Copyright 2012, the Dart project authors. All rights reserved. 7 | Redistribution and use in source and binary forms, with or without 8 | modification, are permitted provided that the following conditions are 9 | met: 10 | * Redistributions of source code must retain the above copyright 11 | notice, this list of conditions and the following disclaimer. 12 | * Redistributions in binary form must reproduce the above 13 | copyright notice, this list of conditions and the following 14 | disclaimer in the documentation and/or other materials provided 15 | with the distribution. 16 | * Neither the name of Google Inc. nor the names of its 17 | contributors may be used to endorse or promote products derived 18 | from this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 21 | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 23 | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 24 | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 25 | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 26 | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 27 | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 28 | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 29 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 30 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | 32 | [1] http://creativecommons.org/licenses/by-nc-nd/3.0/us/ 33 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/common.css: -------------------------------------------------------------------------------- 1 | body { 2 | padding-right: 15px; 3 | padding-left: 15px; 4 | margin: 20px auto 0 auto; 5 | font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; 6 | font-size: 14px; 7 | line-height: 1.428571429; 8 | color: #333; 9 | background-color: #fff; 10 | } 11 | 12 | input[type="text"], textarea { 13 | display: block; 14 | width: 100%; 15 | height: 34px; 16 | padding: 6px 12px; 17 | font-size: 14px; 18 | line-height: 1.428571429; 19 | color: #555; 20 | vertical-align: middle; 21 | background-color: #fff; 22 | background-image: none; 23 | border: 1px solid #ccc; 24 | border-radius: 4px; 25 | -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); 26 | box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); 27 | -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 28 | transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 29 | 30 | font-family: inherit; 31 | font-size: inherit; 32 | line-height: inherit; 33 | } 34 | 35 | 36 | input[type="checkbox"] { 37 | float: left; 38 | margin-left: -20px; 39 | margin: 3px 5px 0 0; 40 | margin-top: 1px \9; 41 | line-height: normal; 42 | padding: 0; 43 | box-sizing: border-box; 44 | } 45 | 46 | 47 | label { 48 | display: inline; 49 | margin-bottom: 0; 50 | font-weight: normal; 51 | cursor: pointer; 52 | } 53 | 54 | select { 55 | display: block; 56 | width: 100%; 57 | height: 34px; 58 | padding: 6px 12px; 59 | font-size: 14px; 60 | line-height: 1.428571429; 61 | color: #555; 62 | vertical-align: middle; 63 | background-color: #fff; 64 | background-image: none; 65 | border: 1px solid #ccc; 66 | border-radius: 4px; 67 | -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); 68 | box-shadow: inset 0 1px 1px rgba(0,0,0,0.075); 69 | -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 70 | transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; 71 | } 72 | 73 | button, input[type='submit'] { 74 | display: inline-block; 75 | padding: 6px 12px; 76 | margin-top: 10px; 77 | margin-bottom: 0; 78 | font-size: 14px; 79 | font-weight: normal; 80 | line-height: 1.428571429; 81 | text-align: center; 82 | white-space: nowrap; 83 | vertical-align: middle; 84 | cursor: pointer; 85 | background-image: none; 86 | border: 1px solid transparent; 87 | border-radius: 4px; 88 | -webkit-user-select: none; 89 | -moz-user-select: none; 90 | -ms-user-select: none; 91 | -o-user-select: none; 92 | user-select: none; 93 | color: #fff; 94 | background-color: #428bca; 95 | border-color: #357ebd; 96 | } 97 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/deleting_a_file_directory_or_symlink.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the FilesSystemEntity `delete()` method to delete a file, directory, or 6 | /// symlink. This method is inherited by File, Directory, and Link. 7 | 8 | import 'dart:io'; 9 | 10 | main() async { 11 | // Create a temporary directory. 12 | var dir = await Directory.systemTemp.createTemp('my_temp_dir'); 13 | 14 | // Confirm it exists. 15 | print(await dir.exists()); 16 | 17 | // Delete the directory. 18 | await dir.delete(); 19 | 20 | // Confirm it no longer exists. 21 | print(await dir.exists()); 22 | } 23 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/directories/creating_a_directory.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the Directory `create()` method to create a directory. 6 | /// To create intermediate directories, set the `recursive` argument to `true` 7 | /// (default is `false`). 8 | 9 | import 'dart:io'; 10 | 11 | main() async { 12 | // Creates dir/ and dir/subdir/. 13 | var directory = await new Directory('dir/subdir').create(recursive: true); 14 | print(directory.path); 15 | } 16 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/directories/creating_a_temporary_directory.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the Directory `createTemp()` method to create a temporary directory. 6 | /// This method appends random characters to the name of the directory to 7 | /// produce a unique directory name. 8 | 9 | import 'dart:io'; 10 | 11 | main() async { 12 | var directory = await Directory.systemTemp.createTemp('my_temp_dir'); 13 | print(directory.path); 14 | } 15 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/directories/listing_the_contents_of_a_directory.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `list()` method to list a directory's contents. The method recurses 6 | /// into subdirectories if the `recursive` argument is `true` (default is 7 | /// `false`). It does not follow symlinks if the `followLinks` argument is 8 | /// `false` (default is `true`). 9 | 10 | import 'dart:io'; 11 | import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. 12 | 13 | main() async { 14 | // Get the system temp directory. 15 | var systemTempDir = Directory.systemTemp; 16 | 17 | // List directory contents, recursing into sub-directories, but not following 18 | // symbolic links. 19 | Stream entityList = 20 | systemTempDir.list(recursive: true, followLinks: false); 21 | await for (FileSystemEntity entity in entityList) print(entity.path); 22 | } 23 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/file.txt: -------------------------------------------------------------------------------- 1 | one banana 2 | two banana 3 | three banana 4 | four -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/creating_a_file.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `create()` method to create a file. 6 | /// To create intermediate directories, set the `recursive` argument to 7 | /// `true` (default is `false`). 8 | 9 | import 'dart:io'; 10 | 11 | main() async { 12 | // Get the system temp directory. 13 | var systemTempDir = Directory.systemTemp; 14 | // Creates dir/, dir/subdir/, and dir/subdir/file.txt in the system 15 | // temp directory. 16 | var file = await new File('${systemTempDir.path}/dir/subdir/file.txt') 17 | .create(recursive: true); 18 | print(file.path); 19 | } 20 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/handling_errors_when_reading_a_file.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:io'; 6 | 7 | main() async { 8 | final filename = 'non_existent_file.txt'; 9 | try { 10 | var file = await new File(filename).readAsString(); 11 | print(file); 12 | } catch (e) { 13 | print('There was a ${e.runtimeType} error'); 14 | print('Could not read $filename'); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_a_string.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `readAsString()` method to read a file as a string. 6 | 7 | import 'dart:io'; 8 | 9 | main() async { 10 | var contents = await new File('file.txt').readAsString(); 11 | print(contents); 12 | } 13 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_bytes.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `readAsBytes()` method to read file contents as bytes. 6 | 7 | import 'dart:io'; 8 | 9 | import 'package:crypto/crypto.dart'; 10 | 11 | main() async { 12 | var bytes = await new File('file.txt').readAsBytes(); 13 | // Do something with the bytes. For example, convert to base64. 14 | String base64 = CryptoUtils.bytesToBase64(bytes); 15 | print(base64); 16 | } 17 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_as_lines.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `readAsLines()` method to read file contents as lines. 6 | 7 | import 'dart:io'; 8 | 9 | main() async { 10 | List lines = await new File('file.txt').readAsLines(); 11 | lines.forEach((String line) => print(line)); 12 | } 13 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/reading_a_file_using_a_stream.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `openRead()` method to read a file's contents a little at a 6 | /// time using a stream. 7 | /// 8 | /// The example below reads the file fragments, decodes them to UTF8, and 9 | /// converts them to individual lines. The `onDone` callback executes when the 10 | /// stream exhausts. The `onError` callback executes when there is an error. 11 | 12 | import 'dart:io'; 13 | import 'dart:convert'; 14 | import 'dart:async'; 15 | 16 | main() async { 17 | final file = new File('file.txt'); 18 | Stream> inputStream = file.openRead(); 19 | 20 | Stream lines = inputStream 21 | // Decode to UTF8. 22 | .transform(UTF8.decoder) 23 | // Convert stream to individual lines. 24 | .transform(new LineSplitter()); 25 | 26 | try { 27 | await for (String line in lines) print('$line: ${line.length} bytes'); 28 | } catch (e) { 29 | print(e.toString()); 30 | } 31 | 32 | print('File is now closed.'); 33 | } 34 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_a_string_to_a_file.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File object's `writeAsString()` method to write a string to a 6 | /// file. After writing the string, the method closes the file. 7 | 8 | import 'dart:io'; 9 | 10 | main() async { 11 | final filename = 'file.txt'; 12 | var file = await new File(filename).writeAsString('some content'); 13 | print("Content written to $file"); 14 | } 15 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_bytes_to_a_file.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `writeAsBytes()` method to write bytes to a file. 6 | 7 | import 'dart:io'; 8 | import 'dart:convert'; 9 | 10 | main() async { 11 | final string = 'Dart!'; 12 | 13 | // Encode to UTF8. 14 | var encodedData = UTF8.encode(string); 15 | var file = await new File('file.txt'); 16 | file.writeAsBytes(encodedData); 17 | var data = await file.readAsBytes(); 18 | 19 | // Decode to a string, and print. 20 | print(UTF8.decode(data)); // Prints 'Dart!'. 21 | } 22 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/files/writing_to_a_file_using_a_stream.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the File `openWrite()` method to create a new IOSink for a file, to 6 | /// write to the file a little at a time. 7 | /// To append to the file, set the `mode` argument to `FileMode.APPEND` 8 | /// (it defaults to `FileMode.WRITE`). 9 | 10 | import 'dart:io'; 11 | 12 | main() { 13 | var file = new File('file.txt'); 14 | var sink = file.openWrite(); 15 | sink.write('FILE ACCESSED ${new DateTime.now()}\n'); 16 | 17 | // Close the IOSink to free system resources. 18 | sink.close(); 19 | } 20 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/finding_the_type_of_a_filesystem_object.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `FileSystemEntity.type()` method to get the type of a file system 6 | /// object. This method is inherited by File, Directory, and Link. 7 | 8 | import 'dart:io'; 9 | import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. 10 | 11 | main() async { 12 | // List the contents of the system temp directory. 13 | Stream entityList = 14 | Directory.systemTemp.list(recursive: true, followLinks: false); 15 | 16 | await for (FileSystemEntity entity in entityList) { 17 | // Get the type of the FileSystemEntity, apply the appropiate label, and 18 | // print the entity path. 19 | FileSystemEntityType type = await FileSystemEntity.type(entity.path); 20 | 21 | String label; 22 | switch (type) { 23 | case FileSystemEntityType.DIRECTORY: 24 | label = 'D'; 25 | break; 26 | case FileSystemEntityType.FILE: 27 | label = 'F'; 28 | break; 29 | case FileSystemEntityType.LINK: 30 | label = 'L'; 31 | break; 32 | default: 33 | label = 'UNKNOWN'; 34 | } 35 | print('$label: ${entity.path}'); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/getting_the_parent_directory.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the FileSystemEntity `parent` property to get the parent of a 6 | /// file, directory, or symlink. This property is inherited by File, Directory, 7 | /// and Link. 8 | 9 | import 'dart:io'; 10 | import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. 11 | 12 | main() async { 13 | // List the contents of the system temp directory. 14 | Stream entityList = 15 | Directory.systemTemp.list(recursive: true, followLinks: false); 16 | 17 | await for (FileSystemEntity entity in entityList) print(entity.parent.path); 18 | } 19 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/renaming_a_file_directory_or_symlink.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the FileSystemEntity `rename()` method to change the name of a 6 | /// file, directory or symlink. This method is inherited by 7 | /// File, Directory, and Link. 8 | 9 | import 'dart:io'; 10 | 11 | main() async { 12 | // Get the system temp directory. 13 | var systemTempDir = Directory.systemTemp; 14 | 15 | // Create a file. 16 | var file = await new File('${systemTempDir.path}/foo.txt').create(); 17 | 18 | // Prints path ending with `foo.txt`. 19 | print('The path is ${file.path}'); 20 | 21 | // Rename the file. 22 | await file.rename('${systemTempDir.path}/bar.txt'); 23 | 24 | // Prints path ending with `bar.txt`. 25 | print('The path is ${file.path}'); 26 | } 27 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/checking_if_a_path_represents_a_symlink.dart: -------------------------------------------------------------------------------- 1 | /// Use the FileSystemEntity `isLink()` method to check if path represents 2 | /// a symlink. 3 | 4 | import 'dart:io'; 5 | import 'dart:async'; // Import not needed but added here to explicitly assign type for clarity below. 6 | 7 | main() async { 8 | // Get the system temp directory. 9 | var systemTempDir = Directory.systemTemp; 10 | 11 | // List the contents of the system temp directory. 12 | Stream entityList = 13 | systemTempDir.list(recursive: true, followLinks: false); 14 | await for (FileSystemEntity entity in entityList) { 15 | // Print the path only if it represents a symlink. 16 | var isLink = await FileSystemEntity.isLink(entity.path); 17 | if (isLink) print(entity.path); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/creating_a_symlink.dart: -------------------------------------------------------------------------------- 1 | /// Use the Link `create()` method to create a symlink. 2 | 3 | import 'dart:io'; 4 | 5 | main() async { 6 | // Get the system temp directory. 7 | var temp = await Directory.systemTemp.createTemp('my_temp_dir'); 8 | 9 | // Generate a couple of paths. 10 | var first = '${temp.path}${Platform.pathSeparator}first'; 11 | var second = '${temp.path}${Platform.pathSeparator}second'; 12 | 13 | // Create a symlink. 14 | Link symLink = await new Link(second).create(first); 15 | print(symLink); 16 | } 17 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/files_directories_and_symlinks/symlinks/getting_the_target_of_a_link.dart: -------------------------------------------------------------------------------- 1 | /// Use the Link `target()` method to get the path that the link points to. 2 | 3 | import 'dart:async'; 4 | import 'dart:io'; 5 | 6 | // Creates temporary directory inside the system temp directory, creates a 7 | // couple of paths in the created directory, and creates a symlink. 8 | Future createSymLink() async { 9 | var temp = await Directory.systemTemp.createTemp('my_temp_dir'); 10 | var first = '${temp.path}${Platform.pathSeparator}first'; 11 | var second = '${temp.path}${Platform.pathSeparator}second'; 12 | return new Link(second).create(first); 13 | } 14 | 15 | main() async { 16 | try { 17 | var link = await createSymLink(); 18 | print(link.path); 19 | var targetPath = await link.target(); 20 | print(targetPath); 21 | } catch (e) { 22 | print(e.message); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/adding_custom_headers.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `headers` argument to the function used to make an HTTP request. 6 | /// The example below adds a 'User-Agent' header to a `get` request. 7 | 8 | import 'dart:convert'; 9 | import 'package:http/http.dart' as http; 10 | 11 | main() async { 12 | var url = 'https://api.github.com/users/dart-lang/repos'; 13 | var response = 14 | await http.get(url, headers: {'User-Agent': 'Dart/1.0 (My Dart client)'}); 15 | 16 | List repos = JSON.decode(response.body); 17 | var heading = 'Repository | Star count | Fork count'; 18 | print(heading); 19 | print(new List.filled(heading.length, '=').join()); 20 | for (var repo in repos) { 21 | print("${repo['name']} | " 22 | "${repo['stargazers_count']} | " 23 | "${repo['forks_count']}"); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/getting_redirection_history.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `HttpClient` class in the 'dart:io' library to make a request, and 6 | /// use the Response `redirects` property to get a list of the redirects. 7 | 8 | import "dart:io" show HttpClient, RedirectInfo; 9 | 10 | main() async { 11 | var client = new HttpClient(); 12 | var request = await client.getUrl(Uri.parse('http://google.com')); 13 | var response = await request.close(); 14 | List redirects = response.redirects; 15 | redirects.forEach((redirect) { 16 | print(redirect.location); // Prints 'http://www.google.com'. 17 | }); 18 | } 19 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/getting_the_response_content_in_binary_format.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `bodyBytes` field on the Response object to get the response 6 | /// in bytes. 7 | 8 | import 'package:http/http.dart' as http; 9 | import 'package:crypto/crypto.dart'; 10 | 11 | main() async { 12 | var url = "https://www.dartlang.org/logos/dart-logo.png"; 13 | var response = await http.get(url); 14 | List bytes = response.bodyBytes; 15 | // Do something with the bytes. For example, convert to base64. 16 | String base64 = CryptoUtils.bytesToBase64(bytes); 17 | print(base64); 18 | } 19 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/getting_the_response_headers.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `headers` field of the Response object to get a headers Map. 6 | /// The map keys are the header fields, and the map values are the values of 7 | /// those fields. 8 | 9 | import 'package:http/http.dart' as http; 10 | 11 | main() async { 12 | var url = 'http://httpbin.org/'; 13 | var response = await http.get(url); 14 | 15 | // Get the headers map. 16 | print(response.headers.keys); 17 | 18 | // Get header values. 19 | print( 20 | "access-control-allow-origin' = ${response.headers['access-control-allow-origin']}"); 21 | print("content-type = ${response.headers['content-type']}"); 22 | print("date = ${response.headers['date']}"); 23 | print("content-length = ${response.headers['content-length']}"); 24 | print("connection = ${response.headers['connection']}"); 25 | } 26 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/handling_an_httprequest_error.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// An HTTP request may return a response, or it may generate an error. 6 | import 'package:http/http.dart' as http; 7 | 8 | handleSuccess(http.Response response) { 9 | print('something went right!'); 10 | print(response.body); 11 | } 12 | 13 | handleFailure(error) { 14 | print('Something went wrong.'); 15 | print(error.message); 16 | } 17 | 18 | main() async { 19 | try { 20 | var response = await http.get("http://some_bogus_website.org"); 21 | handleSuccess(response); 22 | } catch (e) { 23 | handleFailure(e); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/making_a_get_request.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the http package `get()` function to make a GET request. 6 | 7 | import 'package:http/http.dart' as http; 8 | 9 | main() async { 10 | var url = 'http://httpbin.org/'; 11 | var response = await http.get(url); 12 | print("Response status: ${response.statusCode}"); 13 | print("Response body: ${response.body}"); 14 | } 15 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/making_a_post_request.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the http package `post()` function to make a POST request. 6 | 7 | import 'package:http/http.dart' as http; 8 | 9 | main() async { 10 | var url = 'http://httpbin.org/post'; 11 | var response = await http.post(url, body: 'name=doodle&color=blue'); 12 | print("Response status: ${response.statusCode}"); 13 | print("Response body: ${response.body}"); 14 | } 15 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/making_multiple_requests_to_the_same_server.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `Client` class in the http Pub package for making multiple requests 6 | /// to the same server. Using `Client` keeps keep a persistent connection open 7 | /// to the server and is better than making multiple single requests. 8 | 9 | import 'package:http/http.dart' as http; 10 | 11 | printResponseBody(response) { 12 | print(response.body.length); 13 | if (response.body.length > 100) { 14 | print(response.body.substring(0, 100)); 15 | } else { 16 | print(response.body); 17 | } 18 | print('...\n'); 19 | } 20 | 21 | main() async { 22 | var url = 'http://www.google.com/'; 23 | var client = new http.Client(); 24 | try { 25 | var response = await client.get('$url/search'); 26 | printResponseBody(response); 27 | response = await client.get('$url/doodles'); 28 | printResponseBody(response); 29 | } finally { 30 | client.close(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http/reading_the_response_body.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Read the response body using the `read()` function defined in the http Pub 6 | /// package. 7 | 8 | import 'package:http/http.dart' as http; 9 | 10 | main() async { 11 | print(await http.read("http://www.google.com/")); 12 | } 13 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http_server/implementing_a_Hello_World_http_server.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use `HttpServer.bind()` method to bind to a port. 6 | /// The await for listens for connections. 7 | /// Respond to an `HttpRequest` using the `response` property. 8 | 9 | import 'dart:io'; 10 | 11 | main() async { 12 | var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080); 13 | print("Serving at ${server.address}:${server.port}"); 14 | await for (HttpRequest request in server) { 15 | request.response 16 | ..headers.contentType = new ContentType("text", "plain", charset: "utf-8") 17 | ..write('Hello, world') 18 | ..close(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http_server/routing_requests_based_on_url_patterns.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013-2014, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | /// Use the `route` Pub package, and associate callbacks with URL patterns. 6 | 7 | import 'dart:io'; 8 | import 'package:route/server.dart'; 9 | import 'package:route/url_pattern.dart'; 10 | 11 | // Pattern for all posts (plural). 12 | final postsUrl = new UrlPattern(r'/posts\/?'); 13 | 14 | // Pattern for a single post('/post/24', for example). 15 | final postUrl = new UrlPattern(r'/post/(\d+)\/?'); 16 | 17 | // Callback for all posts (plural). 18 | servePosts(req) { 19 | req.response.write("All blog posts"); 20 | req.response.close(); 21 | } 22 | 23 | // Callback for a single post('/post/24', for example). 24 | servePost(req) { 25 | var postId = postUrl.parse(req.uri.path)[0]; 26 | req.response.write('Blog post $postId'); 27 | req.response.close(); 28 | } 29 | 30 | // Callback to handle illegal urls. 31 | serveNotFound(req) { 32 | req.response.statusCode = HttpStatus.NOT_FOUND; 33 | req.response.write('Not found'); 34 | req.response.close(); 35 | } 36 | 37 | main() async { 38 | var server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080); 39 | var router = new Router(server) 40 | // Associate callbacks with URLs. 41 | ..serve(postsUrl, method: 'GET').listen(servePosts) 42 | ..serve(postUrl, method: 'GET').listen(servePost) 43 | ..defaultStream.listen(serveNotFound); 44 | } 45 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http_server/web/foo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

This is foo.html

6 | 7 | 8 | -------------------------------------------------------------------------------- /dart_io_mini_samples/example/http_server/web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 |

This is index.html

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

Choose a Meal!

16 | 17 | 18 | 19 | 20 | 21 |

22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /deferred_loading_samples/lazyloader/web/main.dart: -------------------------------------------------------------------------------- 1 | import 'dart:html'; 2 | 3 | import "package:lazyloader/breakfast.dart" deferred as breakfast; 4 | import "package:lazyloader/lunch.dart" deferred as lunch; 5 | import "package:lazyloader/dinner.dart" deferred as dinner; 6 | 7 | main() { 8 | querySelector('#show-breakfast').onClick.listen((_) async { 9 | await breakfast.loadLibrary(); 10 | onBreakfastLoaded(); 11 | }); 12 | querySelector('#show-lunch').onClick.listen((_) async { 13 | await lunch.loadLibrary(); 14 | onLunchLoaded(); 15 | }); 16 | querySelector('#show-dinner').onClick.listen((_) async { 17 | await dinner.loadLibrary(); 18 | onDinnerLoaded(); 19 | }); 20 | } 21 | 22 | onBreakfastLoaded() { 23 | print('breakfast loaded'); 24 | changeMenu(breakfast.menu); 25 | } 26 | 27 | onLunchLoaded() { 28 | print('lunch loaded'); 29 | changeMenu(lunch.menu); 30 | } 31 | 32 | onDinnerLoaded() { 33 | print('dinner loaded'); 34 | changeMenu(dinner.menu); 35 | } 36 | 37 | changeMenu(String menu) { 38 | var el = querySelector("#text_id"); 39 | el.text = menu; 40 | } 41 | -------------------------------------------------------------------------------- /deferred_loading_samples/lazyloader/web/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | background-color: #F8F8F8; 3 | font-family: 'Open Sans', sans-serif; 4 | font-size: 14px; 5 | font-weight: normal; 6 | line-height: 1.2em; 7 | margin: 15px; 8 | } 9 | 10 | h1, p { 11 | color: #333; 12 | } 13 | 14 | #sample_text_id { 15 | font-size: 24pt; 16 | text-align: center; 17 | margin-top: 140px; 18 | -webkit-user-select: none; 19 | user-select: none; 20 | } 21 | -------------------------------------------------------------------------------- /html5/.pub/bin/sdk-version: -------------------------------------------------------------------------------- 1 | 1.11.3 2 | -------------------------------------------------------------------------------- /html5/AUTHORS: -------------------------------------------------------------------------------- 1 | Shannon -jj Behrens 2 | Matthew Butler 3 | Jason Brooks 4 | Richard Griffith 5 | Seth Ladd 6 | Andrei Mouravski 7 | John McCutchan 8 | Adam Singer 9 | Shailen Tuli 10 | -------------------------------------------------------------------------------- /html5/README.md: -------------------------------------------------------------------------------- 1 | ## Dart HTML5 Samples 2 | 3 | Most of them were ported from [HTML5 Rocks](http://www.html5rocks.com/). 4 | 5 | So far, the samples cover HTML5 topics. We want to expand the scope of the 6 | samples to cover other topics as well. 7 | 8 | * [Using Application Cache](web/appcache/beginner) 9 | * [High DPI Canvas](web/canvas/hidpi) 10 | * [Using Image Filters with Canvas](web/canvas/imagefilters) 11 | * [Basic Drag and Drop](web/dnd/basics) 12 | * [Using the File APIs](web/file/dndfiles) 13 | * [Exploring the FileSystem APIs](web/file/filesystem) 14 | * [A Terminal Emulator that uses the FileSystem APIs](web/file/terminal) 15 | * [Trip Meter: A Basic Geolocation Example](web/geolocation/trip_meter) 16 | * [Simple Todo App using IndexedDB](web/indexeddb/todo) 17 | * [LocalStorage 101](web/localstorage/basics) 18 | * [Pointer Lock And First Person Shooter Controls](web/pointerlock/fps) 19 | * [Working with RequestAnimationFrame](web/speed/animations) 20 | * [HTML5 Video](web/video/basics) 21 | * [Getting Started with the Web Audio API](web/webaudio/intro) 22 | * [3D Solar System Simulation](web/webgl/solar3d) 23 | * [WebSockets 101](web/websockets/basics) 24 | -------------------------------------------------------------------------------- /html5/pubspec.lock: -------------------------------------------------------------------------------- 1 | # Generated by pub 2 | # See http://pub.dartlang.org/doc/glossary.html#lockfile 3 | packages: 4 | args: 5 | description: args 6 | source: hosted 7 | version: "0.13.2" 8 | bot: 9 | description: bot 10 | source: hosted 11 | version: "0.28.0" 12 | bot_io: 13 | description: bot_io 14 | source: hosted 15 | version: "0.26.3+2" 16 | browser: 17 | description: browser 18 | source: hosted 19 | version: "0.10.0+2" 20 | collection: 21 | description: collection 22 | source: hosted 23 | version: "1.1.1" 24 | completion: 25 | description: completion 26 | source: hosted 27 | version: "0.1.4" 28 | crypto: 29 | description: crypto 30 | source: hosted 31 | version: "0.9.0" 32 | csslib: 33 | description: csslib 34 | source: hosted 35 | version: "0.12.1" 36 | hop: 37 | description: hop 38 | source: hosted 39 | version: "0.32.0" 40 | html: 41 | description: html 42 | source: hosted 43 | version: "0.12.1+2" 44 | html5lib: 45 | description: html5lib 46 | source: hosted 47 | version: "0.12.1" 48 | logging: 49 | description: logging 50 | source: hosted 51 | version: "0.9.3" 52 | path: 53 | description: path 54 | source: hosted 55 | version: "1.3.6" 56 | source_span: 57 | description: source_span 58 | source: hosted 59 | version: "1.1.2" 60 | utf: 61 | description: utf 62 | source: hosted 63 | version: "0.9.0+2" 64 | vector_math: 65 | description: vector_math 66 | source: hosted 67 | version: "1.4.3" 68 | -------------------------------------------------------------------------------- /html5/pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: dart_samples 2 | version: 0.0.1-dev 3 | description: Samples for Dart 4 | homepage: https://github.com/dart-lang/dart-samples 5 | environment: 6 | sdk: '>=0.6.17' 7 | dependencies: 8 | browser: any 9 | vector_math: any 10 | hop: any 11 | path: any 12 | html5lib: any 13 | -------------------------------------------------------------------------------- /html5/tool/hop_runner.dart: -------------------------------------------------------------------------------- 1 | library hop_runner; 2 | 3 | import 'dart:io'; 4 | import 'package:path/path.dart' as path; 5 | import 'package:hop/hop.dart'; 6 | import 'package:hop/hop_tasks.dart'; 7 | 8 | import 'package:html5lib/parser.dart' show parse; 9 | 10 | Iterable getHtmlPaths() { 11 | return new Directory('web').listSync(recursive: true, followLinks: false) 12 | .map((File file) => file.path) 13 | .where((_path) => path.extension(_path) == ".html"); 14 | } 15 | 16 | List getDartPaths(htmlPaths) { 17 | List paths = []; 18 | for (var htmlPath in htmlPaths) { 19 | var file = new File(htmlPath).readAsStringSync(); 20 | var contents = parse(file); 21 | var scripts = contents.body.querySelectorAll("script"); 22 | if (!scripts.isEmpty) { 23 | for(var script in scripts) { 24 | if (script.attributes['type'] == 'application/dart') { 25 | // Links to .dart files may not always be in the same directory as 26 | // the .html file. The following line computes the correct path of 27 | // the .dart file. 28 | // So, given a web/app/index.html file that contains a 29 | // 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /html5/web/appcache/beginner/offline.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Appcache for Beginners : Offline 13 | 14 | 15 | 16 |
17 |

This application is offline.

18 |
19 | 20 | 21 | -------------------------------------------------------------------------------- /html5/web/canvas/hidpi/hidpi.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | html, body { 8 | font-family: Helvetica, sans-serif; 9 | } 10 | 11 | h1 { 12 | margin: 2em 0 0.5em 0; 13 | font-size: 16px; 14 | } 15 | 16 | /* 17 | Do the typical thing of setting the image to be a proportion of its 18 | natural dimensions. 19 | */ 20 | #pic { 21 | width: 300px; 22 | height: 90px; 23 | } 24 | 25 | #canvas { 26 | border: 1px solid #CCC; 27 | } -------------------------------------------------------------------------------- /html5/web/canvas/hidpi/hidpi.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the COPYING file. 4 | 5 | // This is a port of "High DPI Canvas" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/canvas/hidpi/ 7 | 8 | import 'dart:html'; 9 | 10 | void drawImage(CanvasElement canvas, ImageElement image, 11 | {bool auto: true, 12 | srcX: 0, srcY: 0, srcW: null, srcH: null, 13 | desX: null, desY: null, desW: null, desH: null}) { 14 | 15 | if (srcW == null) srcW = image.naturalWidth; 16 | if (srcH == null) srcH = image.naturalHeight; 17 | if (desX == null) desX = srcX; 18 | if (desY == null) desY = srcY; 19 | if (desW == null) desW = srcW; 20 | if (desH == null) desH = srcH; 21 | 22 | CanvasRenderingContext2D context = canvas.getContext("2d"); 23 | 24 | num devicePixelRatio = window.devicePixelRatio; 25 | num backingStoreRatio = context.backingStorePixelRatio; 26 | num ratio = devicePixelRatio / backingStoreRatio; 27 | 28 | if (auto && devicePixelRatio != backingStoreRatio) { 29 | num oldWidth = canvas.width; 30 | num oldHeight = canvas.height; 31 | 32 | canvas.width = (oldWidth * ratio).round(); 33 | canvas.height = (oldHeight * ratio).round(); 34 | 35 | canvas.style.width = "${oldWidth}px"; 36 | canvas.style.height = "${oldHeight}px"; 37 | 38 | context.scale(ratio, ratio); 39 | } 40 | 41 | context.drawImageScaledFromSource(image as CanvasImageSource, srcX, srcY, srcW, srcH, desX, desY, desW, desH); 42 | } 43 | 44 | void main() { 45 | CanvasElement canvas = querySelector("#canvas"); 46 | ImageElement pic = querySelector("#pic"); 47 | drawImage(canvas, pic, desX: 10, desY: 10, desW: 300, desH: 90); 48 | } 49 | -------------------------------------------------------------------------------- /html5/web/canvas/hidpi/hidpi.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Canvas Test 13 | 14 | 15 | 16 |

Original Image:

17 | 18 | 19 |

Canvas Version:

20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /html5/web/canvas/hidpi/images/html5rocks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dart-archive/dart-samples/3969c54f98ad3a819370a5d195d81e74a4713903/html5/web/canvas/hidpi/images/html5rocks.png -------------------------------------------------------------------------------- /html5/web/canvas/imagefilters/README.md: -------------------------------------------------------------------------------- 1 | ## Using Image Filters with Canvas 2 | 3 | A port of the examples used in the 4 | [Image Filters with Canvas](http://www.html5rocks.com/en/tutorials/canvas/imagefilters/) 5 | article by Ilmari Heikkinen, originally published on HTML5Rocks. 6 | 7 | 8 | The article describes how to use image filters with an HTML5 Canvas element. 9 | It explains how to process pixels, run simple filters, and blur, 10 | sharpen and emboss an image using convolution filters. 11 | 12 | Please report any [bugs or feature requests](http://dartbug.com/new). 13 | -------------------------------------------------------------------------------- /html5/web/canvas/imagefilters/imagefilters.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | body { 8 | background-color: #F8F8F8; 9 | font-family: 'Open Sans', sans-serif; 10 | font-size: 14px; 11 | font-weight: normal; 12 | line-height: 1.2em; 13 | margin: 15px; 14 | } 15 | 16 | p { 17 | color: #333; 18 | } 19 | 20 | figure { 21 | width: 700px; 22 | margin: 50px auto; 23 | padding-left: 50px; 24 | } 25 | 26 | #container { 27 | width: 100%; 28 | border: 1px solid #ccc; 29 | background-color: #fff; 30 | } 31 | 32 | .show { 33 | display: inline; 34 | } 35 | 36 | .hide { 37 | display: none; 38 | } 39 | -------------------------------------------------------------------------------- /html5/web/canvas/imagefilters/images/demo_small.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dart-archive/dart-samples/3969c54f98ad3a819370a5d195d81e74a4713903/html5/web/canvas/imagefilters/images/demo_small.png -------------------------------------------------------------------------------- /html5/web/canvas/imagefilters/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Image Filters in Dart 13 | 14 | 15 | 16 |

Image Filters in Dart

17 | 18 |

Image Filters with Canvas

19 | 20 |
21 |
22 | 23 |
The original test image
24 |
25 | 26 |
27 | 28 | 29 |
30 | 31 |
32 | 33 | 34 |
35 | 36 |
37 | 38 | 39 |
40 | 41 |
42 | 43 | 44 |
45 | 46 |
47 | 48 | 49 |
50 | 51 |
52 | 53 | 54 |
55 | 56 |
57 | 58 |
59 | 60 | 61 | 62 |
63 | 64 | 65 | 66 |
67 | 68 | 69 | 70 |
71 |
72 | 73 |
74 | 75 |
76 | 77 | 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /html5/web/dnd/basics/README.md: -------------------------------------------------------------------------------- 1 | ## Basic Drag and Drop 2 | 3 | A port of the Drag and Drop example used in the 4 | [Native HTML5 Drag and Drop](http://www.html5rocks.com/en/tutorials/dnd/basics/) 5 | article by Eric Bidelman, originally published on HTML5Rocks. 6 | 7 | HTML5 Drag and drop (DnD) is event-based way of making an element draggable 8 | on a page. Native browser support for this feature means faster, more responsive 9 | web apps. 10 | 11 | Please report any [bugs or feature requests](http://dartbug.com/new). 12 | -------------------------------------------------------------------------------- /html5/web/dnd/basics/basics.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | body { 8 | background-color: #F8F8F8; 9 | font-family: 'Open Sans', sans-serif; 10 | font-size: 14px; 11 | font-weight: normal; 12 | line-height: 1.2em; 13 | margin: 15px; 14 | } 15 | 16 | /* Prevent the text contents of draggable elements from being selectable. */ 17 | [draggable] { 18 | -moz-user-select: none; 19 | -khtml-user-select: none; 20 | -webkit-user-select: none; 21 | user-select: none; 22 | } 23 | 24 | .column { 25 | background-color: #ccc; 26 | -webkit-border-radius: 10px; 27 | -moz-border-radius: 10px; 28 | -ms-border-radius: 10px; 29 | border: 2px solid #666; 30 | border-radius: 10px; 31 | -webkit-box-shadow: inset 0 0 3px #000; 32 | -ms-box-shadow: inset 0 0 3px #000; 33 | box-shadow: inset 0 0 3px #000; 34 | cursor: move; 35 | height: 150px; 36 | float: left; 37 | margin-right: 5px; 38 | text-align: center; 39 | -webkit-transition: -webkit-transform 0.2s ease-out; 40 | -moz-transition: -moz-transform 0.2s ease-out; 41 | -ms-transition: -moz-transform 0.2s ease-out; 42 | transition: transform 0.2s ease-out; 43 | width: 150px; 44 | } 45 | 46 | .column header { 47 | background: -moz-linear-gradient(left center, 48 | rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); 49 | background: -webkit-linear-gradient(linear, left top, right top, 50 | color-stop(0, rgb(0, 0, 0)), 51 | color-stop(0.5, rgb(79, 79, 79)), 52 | color-stop(1, rgb(21, 21, 21))); 53 | background: -webkit-linear-gradient(left center, 54 | rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); 55 | background: -ms-linear-gradient(left center, 56 | rgb(0, 0, 0), rgb(79, 79, 79), rgb(21, 21, 21)); 57 | border-bottom: 1px solid #ddd; 58 | -webkit-border-top-left-radius: 10px; 59 | -moz-border-radius-topleft: 10px; 60 | -ms-border-radius-topleft: 10px; 61 | border-top-left-radius: 10px; 62 | -webkit-border-top-right-radius: 10px; 63 | -moz-border-radius-topright: 10px; 64 | -ms-border-radius-topright: 10px; 65 | border-top-right-radius: 10px; 66 | box-shadow: 5px; 67 | color: #fff; 68 | padding: 5px; 69 | text-shadow: #000 0 1px; 70 | } 71 | 72 | .column.over { 73 | border: 2px dashed #000; 74 | } 75 | 76 | .column.moving { 77 | opacity: 0.25; 78 | -webkit-transform: scale(0.8); 79 | -moz-transform: scale(0.8); 80 | -ms-transform: scale(0.8); 81 | transform: scale(0.8); 82 | } 83 | -------------------------------------------------------------------------------- /html5/web/dnd/basics/basics.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the COPYING file. 4 | 5 | // This is a port of "Native HTML5 Drag and Drop" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/dnd/basics/ 7 | 8 | 9 | import 'dart:html'; 10 | 11 | class Basics { 12 | Element _dragSourceEl; 13 | 14 | void start() { 15 | var cols = document.querySelectorAll('#columns .column'); 16 | for (var col in cols) { 17 | col.onDragStart.listen(_onDragStart); 18 | col.onDragEnd.listen(_onDragEnd); 19 | col.onDragEnter.listen(_onDragEnter); 20 | col.onDragOver.listen(_onDragOver); 21 | col.onDragLeave.listen(_onDragLeave); 22 | col.onDrop.listen(_onDrop); 23 | } 24 | } 25 | 26 | void _onDragStart(MouseEvent event) { 27 | Element dragTarget = event.target; 28 | dragTarget.classes.add('moving'); 29 | _dragSourceEl = dragTarget; 30 | event.dataTransfer.effectAllowed = 'move'; 31 | event.dataTransfer.setData('text/html', dragTarget.innerHtml); 32 | } 33 | 34 | void _onDragEnd(MouseEvent event) { 35 | Element dragTarget = event.target; 36 | dragTarget.classes.remove('moving'); 37 | var cols = document.querySelectorAll('#columns .column'); 38 | for (var col in cols) { 39 | col.classes.remove('over'); 40 | } 41 | } 42 | 43 | void _onDragEnter(MouseEvent event) { 44 | Element dropTarget = event.target; 45 | dropTarget.classes.add('over'); 46 | } 47 | 48 | void _onDragOver(MouseEvent event) { 49 | // This is necessary to allow us to drop. 50 | event.preventDefault(); 51 | event.dataTransfer.dropEffect = 'move'; 52 | } 53 | 54 | void _onDragLeave(MouseEvent event) { 55 | Element dropTarget = event.target; 56 | dropTarget.classes.remove('over'); 57 | } 58 | 59 | void _onDrop(MouseEvent event) { 60 | // Stop the browser from redirecting. 61 | event.stopPropagation(); 62 | 63 | // Don't do anything if dropping onto the same column we're dragging. 64 | Element dropTarget = event.target; 65 | if (_dragSourceEl != dropTarget) { 66 | // Set the source column's HTML to the HTML of the column we dropped on. 67 | _dragSourceEl.innerHtml = dropTarget.innerHtml; 68 | dropTarget.innerHtml = event.dataTransfer.getData('text/html'); 69 | } 70 | } 71 | } 72 | 73 | void main() { 74 | var basics = new Basics(); 75 | basics.start(); 76 | } 77 | -------------------------------------------------------------------------------- /html5/web/dnd/basics/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Drag and Drop: Basics 13 | 14 | 15 | 16 |
17 |
A
18 |
B
19 |
C
20 |
21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/README.md: -------------------------------------------------------------------------------- 1 | ## Using the File APIs 2 | 3 | A Dart port of the Files API examples used in the 4 | [Reading files in JavaScript using the File APIs](http://www.html5rocks.com/en/tutorials/file/dndfiles/) 5 | article by Eric Bidelman, originally published on HTML5Rocks. 6 | 7 | The examples show how to select a file using a form input, or using drag and 8 | drop. See how you can slice a file in separate byte range 9 | chunks for efficient uploading, and monitor progress while uploading a file. 10 | 11 | Please report any [bugs or feature requests](http://dartbug.com/new). 12 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/dndfiles.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the LICENSE file. 5 | */ 6 | 7 | body { 8 | color: #333; 9 | font-family: 'Open Sans', sans-serif; 10 | font-size: 14px; 11 | font-weight: normal; 12 | line-height: 1.2em; 13 | margin: 15px; 14 | } 15 | 16 | output { 17 | display: block; 18 | } 19 | 20 | #byte-content { 21 | margin: 5px 0; 22 | max-height: 200px; 23 | overflow-x: hidden; 24 | overflow-y: auto; 25 | } 26 | 27 | #byte-range { 28 | margin-top: 5px; 29 | } 30 | 31 | #drop-zone { 32 | border: 2px dashed #bbb; 33 | -webkit-border-radius: 5px; 34 | -moz-border-radius: 5px; 35 | border-radius: 5px; 36 | color: #bbb; 37 | font-size: 20pt; 38 | font-weight: bold; 39 | padding: 25px; 40 | text-align: center; 41 | } 42 | 43 | #drop-zone.hover { 44 | background-color: #def; 45 | border-color: #777; 46 | color: #777; 47 | } 48 | 49 | #progress-bar { 50 | background-color: #9cf; 51 | border: 1px solid #000; 52 | font-size: 14px; 53 | margin: 10px 0; 54 | opacity: 0; 55 | -webkit-transition: opacity 0.5s linear; 56 | -moz-transition: opacity 0.5s linear; 57 | -o-transition: opacity 0.5s linear; 58 | transition: opacity 0.5s linear; 59 | padding: 3px; 60 | } 61 | 62 | #progress-bar.loading { 63 | opacity: 1.0; 64 | } 65 | 66 | .thumb { 67 | border: 1px solid #000; 68 | height: 75px; 69 | margin: 10px 5px 0 0; 70 | } 71 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/dndfiles.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // This is a port of "Reading Files in JavaScript Using the File APIs" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ 7 | 8 | import 'dart:convert' show HtmlEscape; 9 | import 'dart:html'; 10 | 11 | 12 | class DndFiles { 13 | FormElement _readForm; 14 | InputElement _fileInput; 15 | Element _dropZone; 16 | OutputElement _output; 17 | HtmlEscape sanitizer = new HtmlEscape(); 18 | 19 | DndFiles() { 20 | _output = document.querySelector('#list'); 21 | _readForm = document.querySelector('#read'); 22 | _fileInput = document.querySelector('#files'); 23 | _fileInput.onChange.listen((e) => _onFileInputChange()); 24 | 25 | _dropZone = document.querySelector('#drop-zone'); 26 | _dropZone.onDragOver.listen(_onDragOver); 27 | _dropZone.onDragEnter.listen((e) => _dropZone.classes.add('hover')); 28 | _dropZone.onDragLeave.listen((e) => _dropZone.classes.remove('hover')); 29 | _dropZone.onDrop.listen(_onDrop); 30 | } 31 | 32 | void _onDragOver(MouseEvent event) { 33 | event.stopPropagation(); 34 | event.preventDefault(); 35 | event.dataTransfer.dropEffect = 'copy'; 36 | } 37 | 38 | void _onDrop(MouseEvent event) { 39 | event.stopPropagation(); 40 | event.preventDefault(); 41 | _dropZone.classes.remove('hover'); 42 | _readForm.reset(); 43 | _onFilesSelected(event.dataTransfer.files); 44 | } 45 | 46 | void _onFileInputChange() { 47 | _onFilesSelected(_fileInput.files); 48 | } 49 | 50 | void _onFilesSelected(List files) { 51 | _output.nodes.clear(); 52 | var list = new Element.tag('ul'); 53 | for (var file in files) { 54 | var item = new Element.tag('li'); 55 | 56 | // If the file is an image, read and display its thumbnail. 57 | if (file.type.startsWith('image')) { 58 | var thumbHolder = new Element.tag('span'); 59 | var reader = new FileReader(); 60 | reader.onLoad.listen((e) { 61 | var thumbnail = new ImageElement(src: reader.result); 62 | thumbnail.classes.add('thumb'); 63 | thumbnail.title = sanitizer.convert(file.name); 64 | thumbHolder.nodes.add(thumbnail); 65 | }); 66 | reader.readAsDataUrl(file); 67 | item.nodes.add(thumbHolder); 68 | } 69 | 70 | // For all file types, display some properties. 71 | var properties = new Element.tag('span'); 72 | properties.innerHtml = (new StringBuffer('') 73 | ..write(sanitizer.convert(file.name)) 74 | ..write(' (') 75 | ..write(file.type != null ? sanitizer.convert(file.type) : 'n/a') 76 | ..write(') ') 77 | ..write(file.size) 78 | ..write(' bytes') 79 | // TODO(jason9t): Re-enable this when issue 5070 is resolved. 80 | // http://code.google.com/p/dart/issues/detail?id=5070 81 | // ..add(', last modified: ') 82 | // ..add(file.lastModifiedDate != null ? 83 | // file.lastModifiedDate.toLocal().toString() : 84 | // 'n/a') 85 | ).toString(); 86 | item.nodes.add(properties); 87 | list.nodes.add(item); 88 | } 89 | _output.nodes.add(list); 90 | } 91 | } 92 | 93 | void main() { 94 | new DndFiles(); 95 | } 96 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/dndfiles.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Reading Files Using the File APIs 13 | 14 | 15 | 16 |

Using Form Input, Drag and Drop, and Reading Files

17 |
18 | 19 |
20 |
Drop files here
21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Reading Files Using the File APIs 13 | 14 | 15 | 16 |

Using the File APIs: Choose an Example

17 |
    18 |
  1. 19 | 20 | Using Form Input, Drag and Drop, and Reading Files 21 | 22 |
  2. 23 |
  3. Slicing a File
  4. 24 |
  5. Monitoring the Progress of a Read
  6. 25 |
26 | 27 | 28 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/monitoring.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // This is a port of "Reading Files in JavaScript Using the File APIs" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ 7 | 8 | import 'dart:html'; 9 | import 'dart:math'; 10 | import 'dart:async'; 11 | 12 | class Monitoring { 13 | InputElement _fileInput; 14 | Element _progressBar; 15 | FileReader _reader; 16 | 17 | Monitoring() { 18 | _progressBar = querySelector('#progress-bar'); 19 | _fileInput = document.querySelector('#files'); 20 | _fileInput.onChange.listen((e) => _onFilesSelected()); 21 | var cancelButton = querySelector('#cancel-read'); 22 | cancelButton.onClick.listen((e) => _onCancel()); 23 | } 24 | 25 | void _setProgress(int value) { 26 | value = min(100, max(0, value)); 27 | _progressBar.style.width = '${value}%'; 28 | _progressBar.text = '${value}%'; 29 | if (value == 0 || value == 100) { 30 | new Timer(const Duration(milliseconds: 2000), () => _progressBar.classes.remove('loading')); 31 | } 32 | } 33 | 34 | void _onFilesSelected() { 35 | // Reset progress indicator on new file selection. 36 | _setProgress(0); 37 | _progressBar.classes.remove('loading'); 38 | 39 | // Set up handlers and begin reading the file. 40 | var file = _fileInput.files[0]; 41 | _reader = new FileReader(); 42 | _reader.onError.listen((e) => _onError()); 43 | _reader.onProgress.listen(_onProgress); 44 | _reader.onAbort.listen((e) => window.alert('File read cancelled.')); 45 | _reader.onLoadStart.listen((e) => _progressBar.classes.add('loading')); 46 | _reader.onLoad.listen((e) => _setProgress(100)); 47 | _reader.readAsText(file); 48 | } 49 | 50 | void _onCancel() { 51 | if (_reader != null) { 52 | _reader.abort(); 53 | } 54 | } 55 | 56 | void _onProgress(ProgressEvent event) { 57 | if (event.lengthComputable) { 58 | var percentLoaded = (100 * event.loaded / event.total).round().toInt(); 59 | _setProgress(percentLoaded); 60 | } 61 | } 62 | 63 | void _onError() { 64 | switch(_reader.error.code) { 65 | case FileError.NOT_FOUND_ERR: 66 | window.alert('File not found!'); 67 | break; 68 | case FileError.NOT_READABLE_ERR: 69 | window.alert('File is not readable.'); 70 | break; 71 | case FileError.ABORT_ERR: 72 | break; // no-op. 73 | default: 74 | window.alert('An error occurred reading this file.'); 75 | break; 76 | } 77 | } 78 | } 79 | 80 | void main() { 81 | new Monitoring(); 82 | } 83 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/monitoring.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Reading Files Using the File APIs 13 | 14 | 15 | 16 |

Monitoring the Progress of a Read

17 | 18 | 19 |
0%
20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/slicing.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // This is a port of "Reading Files in JavaScript Using the File APIs" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/file/dndfiles/ 7 | 8 | import 'dart:html'; 9 | 10 | class Slicing { 11 | InputElement _fileInput; 12 | Element _content; 13 | Element _byteRange; 14 | 15 | Slicing() { 16 | _content = querySelector('#byte-content'); 17 | _byteRange = querySelector('#byte-range'); 18 | 19 | _fileInput = querySelector('#files'); 20 | _fileInput.onChange.listen((e) { 21 | _content.text = ''; 22 | _byteRange.text = ''; 23 | }); 24 | 25 | var buttons = querySelector('#read-bytes-buttons'); 26 | buttons.onClick.listen(_onClick); 27 | } 28 | 29 | void _onClick(MouseEvent event) { 30 | Element clicked = event.target; 31 | if (clicked is ButtonElement) { 32 | var start = clicked.attributes['data-startbyte']; 33 | var end = clicked.attributes['data-endbyte']; 34 | _readBlob( 35 | start != null ? int.parse(start) : null, 36 | end != null ? int.parse(end) : null); 37 | } 38 | } 39 | 40 | void _readBlob([int startByte, int endByte]) { 41 | var files = _fileInput.files; 42 | if (files.length == 0) { 43 | window.alert('Please select a file!'); 44 | return; 45 | } 46 | 47 | var file = files[0]; 48 | var start = startByte != null ? startByte : 0; 49 | var end = endByte != null ? endByte : file.size; 50 | var reader = new FileReader(); 51 | reader.onLoad.listen((e) { 52 | _content.text = reader.result; 53 | _byteRange.text = 54 | 'Read bytes ${start + 1} - ${end + 1} of ${file.size}.'; 55 | }); 56 | var slice = file.slice(start, end); 57 | reader.readAsDataUrl(slice); 58 | } 59 | } 60 | 61 | void main() { 62 | new Slicing(); 63 | } 64 | -------------------------------------------------------------------------------- /html5/web/file/dndfiles/slicing.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Reading Files Using the File APIs 13 | 14 | 15 | 16 |

Slicing a File

17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 |
26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /html5/web/file/filesystem/README.md: -------------------------------------------------------------------------------- 1 | ## Exploring the FileSystem APIs 2 | 3 | A port of the FileSystem example used in the 4 | [Exploring the FileSystem APIs](http://www.html5rocks.com/en/tutorials/file/filesystem/) 5 | article by Eric Bidelman, originally published on HTML5Rocks. 6 | 7 | With the FileSystem API, a web app can create, read, navigate, and write to a 8 | sandboxed section of the user's local file system. 9 | 10 | Please report any [bugs or feature requests](http://dartbug.com/new). 11 | -------------------------------------------------------------------------------- /html5/web/file/filesystem/filesystem.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the LICENSE file. 5 | */ 6 | 7 | .example { 8 | padding: 10px; 9 | border: 1px solid #CCC; 10 | } 11 | 12 | #example-list-fs ul { 13 | padding-left: 0; 14 | } 15 | 16 | #example-list-fs li { 17 | list-style: none; 18 | } 19 | 20 | #example-list-fs img { 21 | vertical-align: middle; 22 | } 23 | 24 | button { 25 | padding: 5px 8px; 26 | cursor: pointer; 27 | text-shadow: 1px 1px white; 28 | font-weight: 700; 29 | font-size: 10pt; 30 | } 31 | 32 | body { 33 | font: 14px Arial; 34 | } 35 | -------------------------------------------------------------------------------- /html5/web/file/filesystem/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Filesystem 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 |
    21 |
    22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /html5/web/file/terminal/README.md: -------------------------------------------------------------------------------- 1 | ## A Terminal Emulator that uses the FileSystem APIs 2 | 3 | A port of the Terminal example used in the 4 | [Exploring the FileSystem APIs](http://www.html5rocks.com/en/tutorials/file/filesystem/) 5 | article by Eric Bidelman, originally published on HTML5Rocks. 6 | 7 | With the FileSystem API, a web app can create, read, navigate, and write to a 8 | sandboxed section of the user's local file system. 9 | 10 | This example simulates a UNIX terminal, and replicates common UNIX filesystem 11 | operations such as `cd`, `mkdir`, `rm`, `open`, and `cat` using the FileSystem 12 | API. To add content, open the app, then drag and drop files from your 13 | desktop onto the terminal window. 14 | 15 | Please report any [bugs or feature requests](http://dartbug.com/new). 16 | -------------------------------------------------------------------------------- /html5/web/file/terminal/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | 12 | 13 | 14 | 15 | 16 | TerminalFilesystem 17 | 18 | 19 | 20 | 21 |

    TerminalFilesystem

    22 |
    23 | 24 |
    25 |
    $>
    26 |
    27 |
    28 | 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /html5/web/file/terminal/terminal.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | ::selection { 8 | background: #FF5E99; 9 | } 10 | 11 | html, body { 12 | width: 100%; 13 | height: 100%; 14 | margin: 0; 15 | } 16 | 17 | body { 18 | font-size: 12px; 19 | font-family: Inconsolata, monospace; 20 | color: white; 21 | background-color: black; 22 | } 23 | 24 | .dropping { 25 | background-image: -webkit-gradient( 26 | linear, left bottom, left top, 27 | color-stop(0.13, rgb(209,144,23)), 28 | color-stop(0.57, rgb(251,173,51)), 29 | color-stop(0.79, rgb(255,208,77)) 30 | ); 31 | background-image: -moz-linear-gradient( 32 | center bottom, 33 | rgb(209,144,23) 13%, 34 | rgb(251,173,51) 57%, 35 | rgb(255,208,77) 79% 36 | ); 37 | } 38 | 39 | #container { 40 | padding: 1em 1.5em 1em 1em; 41 | } 42 | 43 | #container output { 44 | clear: both; 45 | width: 100%; 46 | } 47 | #container output h3 { 48 | margin: 0; 49 | } 50 | 51 | #container output pre { 52 | margin: 0; 53 | } 54 | 55 | .input-line { 56 | display: -webkit-box; 57 | -webkit-box-orient: horizontal; 58 | -webkit-box-align: stretch; 59 | display: -moz-box; 60 | -moz-box-orient: horizontal; 61 | -moz-box-align: stretch; 62 | display: box; 63 | box-orient: horizontal; 64 | box-align: stretch; 65 | clear: both; 66 | } 67 | 68 | .input-line > div:nth-child(2) { 69 | -webkit-box-flex: 1; 70 | -moz-box-flex: 1; 71 | box-flex: 1; 72 | } 73 | 74 | .prompt { 75 | white-space: nowrap; 76 | color: green; 77 | margin-right: 7px; 78 | display: -webkit-box; 79 | -webkit-box-pack: center; 80 | -webkit-box-orient: vertical; 81 | display: -moz-box; 82 | -moz-box-pack: center; 83 | -moz-box-orient: vertical; 84 | display: box; 85 | box-pack: center; 86 | box-orient: vertical; 87 | -webkit-user-select: none; 88 | -moz-user-select: none; 89 | user-select: none; 90 | } 91 | 92 | .cmdline { 93 | outline: none; 94 | background-color: transparent; 95 | margin: 0; 96 | width: 100%; 97 | font: inherit; 98 | border: none; 99 | color: inherit; 100 | } 101 | 102 | .folder { 103 | color: blue; 104 | } 105 | 106 | .ls-files { 107 | height: 45px; 108 | /* Default, but changed by js depending on length of filename */ 109 | -webkit-column-width: 100px; 110 | -moz-column-width: 100px; 111 | -o-column-width: 100px; 112 | column-width: 100px; 113 | } 114 | 115 | /* Themes */ 116 | body.cream { 117 | color: black; 118 | background-color: #fffff3; 119 | } 120 | 121 | .cream .prompt { 122 | color: purple; 123 | } 124 | 125 | .cream .cmdline { 126 | color: black; 127 | } -------------------------------------------------------------------------------- /html5/web/file/terminal/terminal_filesystem.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // This is a port of "Exploring the FileSystem APIs" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/file/filesystem/ 7 | 8 | library terminal_filesystem; 9 | 10 | import 'dart:convert' show HtmlEscape; 11 | import 'dart:html'; 12 | 13 | part 'terminal.dart'; 14 | 15 | class TerminalFilesystem { 16 | Terminal term; 17 | 18 | void run() { 19 | term = new Terminal('#input-line', '#output', '#cmdline'); 20 | term.initializeFilesystem(false, 1024 * 1024); 21 | 22 | if (!window.location.hash.isEmpty) { 23 | var theme = window.location.hash.substring(1, window.location.hash.length).split('=')[1]; 24 | term.setTheme(theme); 25 | } else if (window.localStorage.containsKey('theme')) { 26 | term.setTheme(window.localStorage['theme']); 27 | } 28 | 29 | // Setup the DnD listeners for file drop. 30 | var body = document.body; 31 | body.onDragEnter.listen(onDragEnter); 32 | body.onDragOver.listen(onDragOver); 33 | body.onDrop.listen(onDrop); 34 | } 35 | 36 | void onDragEnter(MouseEvent event) { 37 | event.stopPropagation(); 38 | event.preventDefault(); 39 | Element dropTarget = event.target; 40 | dropTarget.classes.add('dropping'); 41 | } 42 | 43 | void onDragOver(MouseEvent event) { 44 | event.stopPropagation(); 45 | event.preventDefault(); 46 | 47 | // Explicitly show this is a copy. 48 | event.dataTransfer.dropEffect = 'copy'; 49 | } 50 | 51 | void onDrop(MouseEvent event) { 52 | event.stopPropagation(); 53 | event.preventDefault(); 54 | Element dropTarget = event.target; 55 | dropTarget.classes.remove('dropping'); 56 | term.addDroppedFiles(event.dataTransfer.files); 57 | term.writeOutput('
    File(s) added!
    '); 58 | } 59 | } 60 | 61 | void main() { 62 | new TerminalFilesystem().run(); 63 | } 64 | -------------------------------------------------------------------------------- /html5/web/geolocation/trip_meter/README.md: -------------------------------------------------------------------------------- 1 | ## Trip Meter: A Basic Geolocaton Example 2 | 3 | A port of the Geolocation example used in the 4 | [A Simple Trip Meter Using the Geolocation API] (http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/) 5 | article by Michael Mahemoff, originally published on HTML5Rocks. 6 | 7 | The Geolocation API lets you track a user's location. The API is 8 | device-agnostic; the underlying mechanism might be via GPS, 9 | wifi, or simply asking the user to enter their location manually. Since 10 | these lookups can take some time, the API is asynchronous, and you 11 | pass it a callback method whenever you request a location. 12 | 13 | The Trip Meter example display's the user's initial location, and it 14 | tracks the distance the user has travelled since the page was loaded. 15 | 16 | Please report any [bugs or feature requests](http://dartbug.com/new). 17 | -------------------------------------------------------------------------------- /html5/web/geolocation/trip_meter/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | TripMeter 13 | 14 | 15 | 16 |
    17 |

    18 | Starting Location (lat, lon):
    19 | ???°, ???° 20 |

    21 |

    22 | Current Location (lat, lon):
    23 | ???°, ???° 24 |

    25 |

    26 | Distance from starting location:
    27 | 0 km 28 |

    29 |
    30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /html5/web/geolocation/trip_meter/trip_meter.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | #tripmeter { 8 | border: 3px double black; 9 | padding: 10px; 10 | margin: 10px 0; 11 | } 12 | 13 | p { 14 | color: #222; 15 | font: 14px Arial; 16 | } 17 | 18 | span { 19 | color: #00C; 20 | } -------------------------------------------------------------------------------- /html5/web/geolocation/trip_meter/trip_meter.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the COPYING file. 4 | 5 | // This is a port of "A Simple Trip Meter Using the Geolocation API" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/geolocation/trip_meter/ 7 | 8 | import 'dart:html'; 9 | import 'dart:math'; 10 | 11 | // Reused code - copyright Moveable Type Scripts 12 | // http://www.movable-type.co.uk/scripts/latlong.html 13 | // Under Creative Commons License http://creativecommons.org/licenses/by/3.0/ 14 | num calculateDistance(num lat1, num lon1, num lat2, num lon2) { 15 | const EARTH_RADIUS = 6371; // km 16 | num latDiff = lat2 - lat1; 17 | num lonDiff = lon2 - lon1; 18 | 19 | // a is the square of half the chord length between the points. 20 | var a = pow(sin(latDiff / 2), 2) + 21 | cos(lat1) * cos (lat2) * 22 | pow(sin(lonDiff / 2), 2); 23 | 24 | var angularDistance = 2 * atan2(sqrt(a), sqrt(1 - a)); 25 | return EARTH_RADIUS * angularDistance; 26 | } 27 | 28 | // Don't use alert() in real code ;) 29 | void alertError(PositionError error) { 30 | window.alert("Error occurred. Error code: ${error.code}"); 31 | } 32 | 33 | void main(){ 34 | Geoposition startPosition; 35 | 36 | window.navigator.geolocation.getCurrentPosition() 37 | .then((Geoposition position) { 38 | startPosition = position; 39 | querySelector("#start-lat").text = "${startPosition.coords.latitude}"; 40 | querySelector("#start-lon").text = "${startPosition.coords.longitude}"; 41 | }, onError: (error) => alertError(error)); 42 | 43 | window.navigator.geolocation.watchPosition().listen((Geoposition position) { 44 | querySelector("#current-lat").text = "${position.coords.latitude}"; 45 | querySelector("#current-lon").text = "${position.coords.longitude}"; 46 | num distance = calculateDistance( 47 | startPosition.coords.latitude, 48 | startPosition.coords.longitude, 49 | position.coords.latitude, 50 | position.coords.longitude); 51 | querySelector("#distance").text = "$distance"; 52 | }, onError: (error) => alertError(error)); 53 | } 54 | -------------------------------------------------------------------------------- /html5/web/indexeddb/todo/README.md: -------------------------------------------------------------------------------- 1 | ## Simple Todo App using IndexedDB 2 | 3 | A port of the Todo example used in the 4 | [A Simple TODO list using HTML5 IndexedDB](http://www.html5rocks.com/en/tutorials/file/filesystem/) 5 | article by Paul Kinlan, originally published on HTML5Rocks. 6 | 7 | The example demonstrates how to create a very simple todo 8 | list manager using IndexedDB. 9 | 10 | IndexedDB is a data store that developers can use to store and manipulate data 11 | on the client side. IndexedDB is usually used as an Asynchronous API where the 12 | data is delivered to a defined callback function. 13 | 14 | You can open the example in Dart Editor and run it by clicking `index.html`. 15 | Or, you can try this 16 | [live demo](http://www.html5rocks.com/en/tutorials/indexeddb/todo/). 17 | 18 | Please report any [bugs or feature requests](http://dartbug.com/new). 19 | -------------------------------------------------------------------------------- /html5/web/indexeddb/todo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | A Simple ToDo List Using HTML5 IndexedDB 13 | 14 | 15 | 16 | 18 | 19 |
      20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /html5/web/indexeddb/todo/todo.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | body { 8 | color: #222; 9 | font: 14px Arial; 10 | } 11 | 12 | a { 13 | color: #3D5C9D; 14 | cursor: pointer; 15 | text-decoration: none; 16 | } 17 | 18 | li a { 19 | margin-left: 8px; 20 | } 21 | 22 | #todo { 23 | width: 200px; 24 | } 25 | -------------------------------------------------------------------------------- /html5/web/indexeddb/todo/todo.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the COPYING file. 4 | 5 | // This is a port of "A Simple ToDo List Using HTML5 IndexedDB" to Dart. 6 | // See: http://www.html5rocks.com/en/tutorials/indexeddb/todo/ 7 | 8 | import 'dart:html'; 9 | import 'dart:indexed_db' as idb; 10 | import 'dart:async'; 11 | 12 | class TodoList { 13 | static final String _TODOS_DB = "todo"; 14 | static final String _TODOS_STORE = "todos"; 15 | 16 | idb.Database _db; 17 | int _version = 2; 18 | InputElement _input; 19 | Element _todoItems; 20 | 21 | TodoList() { 22 | _todoItems = querySelector('#todo-items'); 23 | _input = querySelector('#todo'); 24 | querySelector('input#submit').onClick.listen((e) => _onAddTodo()); 25 | } 26 | 27 | Future open() { 28 | return window.indexedDB.open(_TODOS_DB, version: _version, 29 | onUpgradeNeeded: _onUpgradeNeeded) 30 | .then(_onDbOpened) 31 | .catchError(_onError); 32 | } 33 | 34 | void _onError(e) { 35 | // Get the user's attention for the sake of this tutorial. (Of course we 36 | // would *never* use window.alert() in real life.) 37 | window.alert('Oh no! Something went wrong. See the console for details.'); 38 | window.console.log('An error occurred: {$e}'); 39 | } 40 | 41 | void _onDbOpened(idb.Database db) { 42 | _db = db; 43 | _getAllTodoItems(); 44 | } 45 | 46 | void _onUpgradeNeeded(idb.VersionChangeEvent e) { 47 | idb.Database db = (e.target as idb.OpenDBRequest).result; 48 | if (!db.objectStoreNames.contains(_TODOS_STORE)) { 49 | db.createObjectStore(_TODOS_STORE, keyPath: 'timeStamp'); 50 | } 51 | } 52 | 53 | void _onAddTodo() { 54 | var value = _input.value.trim(); 55 | if (value.length > 0) { 56 | _addTodo(value); 57 | } 58 | _input.value = ''; 59 | } 60 | 61 | Future _addTodo(String text) { 62 | var trans = _db.transaction(_TODOS_STORE, 'readwrite'); 63 | var store = trans.objectStore(_TODOS_STORE); 64 | return store.put({ 65 | 'text': text, 66 | 'timeStamp': new DateTime.now().millisecondsSinceEpoch.toString() 67 | }).then((_) => _getAllTodoItems()) 68 | .catchError((e) => _onError); 69 | } 70 | 71 | void _deleteTodo(String id) { 72 | var trans = _db.transaction(_TODOS_STORE, 'readwrite'); 73 | var store = trans.objectStore(_TODOS_STORE); 74 | var request = store.delete(id); 75 | request.then((e) => _getAllTodoItems(), onError: _onError); 76 | } 77 | 78 | void _getAllTodoItems() { 79 | _todoItems.nodes.clear(); 80 | 81 | var trans = _db.transaction(_TODOS_STORE, 'readwrite'); 82 | var store = trans.objectStore(_TODOS_STORE); 83 | 84 | // Get everything in the store. 85 | var request = store.openCursor(autoAdvance:true).listen((cursor) { 86 | _renderTodo(cursor.value); 87 | }, onError: _onError); 88 | } 89 | 90 | void _renderTodo(Map todoItem) { 91 | var textDisplay = new Element.tag('span'); 92 | textDisplay.text = todoItem['text']; 93 | 94 | var deleteControl = new Element.tag('a'); 95 | deleteControl.text = '[Delete]'; 96 | deleteControl.onClick.listen((e) => _deleteTodo(todoItem['timeStamp'])); 97 | 98 | var item = new Element.tag('li'); 99 | item.nodes.add(textDisplay); 100 | item.nodes.add(deleteControl); 101 | _todoItems.nodes.add(item); 102 | } 103 | } 104 | 105 | void main() { 106 | new TodoList().open(); 107 | } 108 | -------------------------------------------------------------------------------- /html5/web/localstorage/basics/README.md: -------------------------------------------------------------------------------- 1 | ## LocalStorage 101 2 | 3 | A basic example showing the use of LocalStorage for persistence. 4 | 5 | LocalStorage is a simple key/value storage interface for Strings. 6 | Though widely supported, LocalStorage is a synchronous API. Because it involves 7 | I/O, this interface should not be used for high throughput operations. 8 | Consider IndexedDB as an alternative. For simple string keys and values, and as 9 | a replacement for cookies, LocalStorage is useful. 10 | 11 | When you enter a value in the username input in the example, 12 | it is stored in LocalStorage. 13 | The value is then retrieved from LocalStorage and displayed on the page. 14 | 15 | Please report any [bugs or feature requests](http://dartbug.com/new). 16 | -------------------------------------------------------------------------------- /html5/web/localstorage/basics/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Local Storage in Dart 13 | 14 | 15 |

      Local Storage in Dart

      16 | 17 |

      18 | From local storage: 19 |

      20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /html5/web/localstorage/basics/localstorage.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | import 'dart:html'; 6 | 7 | void main() { 8 | InputElement username = querySelector('#username'); 9 | InputElement submit = querySelector('#save'); 10 | Element output = querySelector('#username-output'); 11 | Storage localStorage = window.localStorage; 12 | 13 | // Local storage is a Map, supporting string keys and values. 14 | String savedUsername = localStorage['username']; 15 | 16 | if (savedUsername != null) { 17 | output.text = savedUsername; 18 | } 19 | 20 | submit.onClick.listen((Event e) { 21 | output.text = username.value; 22 | localStorage['username'] = username.value; 23 | }); 24 | } 25 | -------------------------------------------------------------------------------- /html5/web/pointerlock/fps/fps.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the LICENSE file. 5 | */ 6 | 7 | body { 8 | background-color: #F8F8F8; 9 | font-family: 'Open Sans', sans-serif; 10 | font-size: 14px; 11 | font-weight: normal; 12 | line-height: 1.2em; 13 | margin: 15px; 14 | } 15 | 16 | p { 17 | color: #333; 18 | } 19 | 20 | #text { 21 | font-size: 24pt; 22 | text-align: center; 23 | margin-top: 140px; 24 | } 25 | -------------------------------------------------------------------------------- /html5/web/pointerlock/fps/fps_camera.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | part of fps; 6 | 7 | class Camera { 8 | Vector3 eyePosition; 9 | Vector3 upDirection; 10 | Vector3 lookAtPosition; 11 | num zNear; 12 | num zFar; 13 | num aspectRatio; 14 | num fOV; 15 | 16 | Camera() { 17 | eyePosition = new Vector3(0.0, 2.0, 0.0); 18 | lookAtPosition = new Vector3(1.0, 2.0, -1.0); 19 | upDirection = new Vector3(0.0, 1.0, 0.0); 20 | 21 | fOV = 0.785398163; // 90 degrees 22 | zNear = 1.0; 23 | zFar = 1000.0; 24 | aspectRatio = 1.7777778; 25 | } 26 | 27 | String toString() { 28 | return '$eyePosition -> $lookAtPosition'; 29 | } 30 | 31 | num get yaw { 32 | Vector3 z = new Vector3(0.0, 0.0, 1.0); 33 | Vector3 forward = frontDirection; 34 | forward.normalize(); 35 | return degrees(Math.acos(forward.dot(z))); 36 | } 37 | 38 | num get pitch { 39 | Vector3 y = new Vector3(0.0, 1.0, 0.0); 40 | Vector3 forward = frontDirection; 41 | forward.normalize(); 42 | return degrees(Math.acos(forward.dot(y))); 43 | } 44 | 45 | Matrix4 get projectionMatrix { 46 | return makePerspective(fOV, aspectRatio, zNear, zFar); 47 | } 48 | 49 | Matrix4 get lookAtMatrix { 50 | return makeLookAt(eyePosition, lookAtPosition, upDirection); 51 | } 52 | 53 | void copyProjectionMatrixIntoArray(Float32List pm) { 54 | Matrix4 m = makePerspective(fOV, aspectRatio, zNear, zFar); 55 | m.copyIntoArray(pm); 56 | } 57 | 58 | void copyViewMatrixIntoArray(Float32List vm) { 59 | Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); 60 | m.copyIntoArray(vm); 61 | } 62 | 63 | void copyNormalMatrixIntoArray(Float32List nm) { 64 | Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); 65 | m.copyIntoArray(nm); 66 | } 67 | 68 | void copyProjectionMatrix(Matrix4 pm) { 69 | Matrix4 m = makePerspective(fOV, aspectRatio, zNear, zFar); 70 | m.copyInto(pm); 71 | } 72 | 73 | void copyViewMatrix(Matrix4 vm) { 74 | Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); 75 | m.copyInto(vm); 76 | } 77 | 78 | void copyNormalMatrix(Matrix4 nm) { 79 | Matrix4 m = makeLookAt(eyePosition, lookAtPosition, upDirection); 80 | m.copyInto(nm); 81 | } 82 | 83 | void copyEyePosition(Vector3 ep) { 84 | eyePosition.copyInto(ep); 85 | } 86 | 87 | void copyLookAtPosition(Vector3 lap) { 88 | lookAtPosition.copyInto(lap); 89 | } 90 | 91 | Vector3 get frontDirection => lookAtPosition - eyePosition; 92 | } 93 | -------------------------------------------------------------------------------- /html5/web/pointerlock/fps/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Pointer Lock First Person Shooter Controls 7 | 8 | 9 | 10 |

      Click on view to active

      11 |

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

      12 |

      Mouse: Rotates view

      13 |
      14 | 15 |
      16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /html5/web/speed/animations/README.md: -------------------------------------------------------------------------------- 1 | ## Working with RequestAnimationFrame 2 | 3 | A port of the example used in the 4 | [Leaner, Meaner, Faster Animations with requestAnimationFrame](http://www.html5rocks.com/en/tutorials/speed/animations/) 5 | article by Paul Lewis, originally published on HTML5Rocks. 6 | 7 | The article explains how to correctly use requestAnimationFrame for your 8 | animations. Here is a summary of the article contents: 9 | 10 | * Decouple your events from animations 11 | * Avoid animations that result in reflow-repaint loops 12 | * Update your RAF calls to expect a high resolution timestamp as the first 13 | parameter 14 | * Only call RAF when you have visual updates to do 15 | 16 | Use the up and down keys to activate the animation. The up key moves the 17 | circles from right to left, and the down key moves them from left to right. 18 | 19 | Please report any [bugs or feature requests](http://dartbug.com/new). 20 | -------------------------------------------------------------------------------- /html5/web/speed/animations/animations.css: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 3 | for details. All rights reserved. Use of this source code is governed by a 4 | BSD-style license that can be found in the COPYING file. 5 | */ 6 | 7 | .mover { 8 | position: absolute; 9 | width: 100px; 10 | height: 100px; 11 | 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; 12 | left: 90%; 13 | -webkit-transition: left 1.3s ease-out; 14 | -moz-transition: left 1.3s ease-out; 15 | -ms-transition: left 1.3s ease-out; 16 | -o-transition: left 1.3s ease-out; 17 | transition: left 1.3s ease-out; 18 | } 19 | 20 | .mover.left { 21 | left: 10%; 22 | } -------------------------------------------------------------------------------- /html5/web/speed/animations/animations.dart: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file 2 | // for details. All rights reserved. Use of this source code is governed by a 3 | // BSD-style license that can be found in the LICENSE file. 4 | 5 | // This is a port of "Leaner, Meaner, Faster Animations with 6 | // requestAnimationFrame" to Dart. 7 | // See: http://www.html5rocks.com/en/tutorials/speed/animations/ 8 | 9 | import 'dart:html'; 10 | 11 | class AnimationExample { 12 | final _numMovers = 500; 13 | List _movers; 14 | List _moverTops; 15 | num _lastScrollY = 0; 16 | bool _ticking = false; 17 | 18 | AnimationExample() { 19 | _movers = new List(_numMovers); 20 | _moverTops = new List(_numMovers); 21 | for (var i = 0; i < _numMovers; i++) { 22 | var mover = new Element.tag("div"); 23 | mover.classes.add("mover"); 24 | mover.style.top = "${i * 10}px"; 25 | document.body.nodes.add(mover); 26 | _movers[i] = mover; 27 | } 28 | window.onScroll.listen((e) => _onScroll()); 29 | } 30 | 31 | void _onScroll() { 32 | _lastScrollY = window.scrollY; 33 | _requestTick(); 34 | } 35 | 36 | void _requestTick() { 37 | if (!_ticking) { 38 | window.requestAnimationFrame(_update); 39 | _ticking = true; 40 | } 41 | } 42 | 43 | void _update(num time) { 44 | var halfWindowHeight = window.innerHeight * 0.5; 45 | var offset = 0; 46 | 47 | for (var i = 0; i < _movers.length; i++) { 48 | Element mover = _movers[i]; 49 | _moverTops[i] = mover.offsetTop; 50 | } 51 | 52 | // Using separate for loops is a subtle browser optimization. See the 53 | // tutorial. 54 | for (var i = 0; i < _movers.length; i++) { 55 | Element mover = _movers[i]; 56 | if (_lastScrollY > _moverTops[i] - halfWindowHeight) { 57 | mover.classes.add('left'); 58 | } else { 59 | mover.classes.remove('left'); 60 | } 61 | } 62 | 63 | _ticking = false; 64 | } 65 | } 66 | 67 | void main() { 68 | new AnimationExample(); 69 | } -------------------------------------------------------------------------------- /html5/web/speed/animations/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | 11 | 12 | Animations 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /html5/web/video/basics/README.md: -------------------------------------------------------------------------------- 1 | ## HTML5 Video 2 | 3 | A port of an example used in the 4 | [HTML5 Video](http://www.html5rocks.com/en/tutorials/video/basics/) 5 | article by Ernest Delgado, originally published on HTML5Rocks. 6 | 7 | The example shows how to use the `