From 4586968860aeb3b35a5bfa2d6e9ddd5b0fb8b145 Mon Sep 17 00:00:00 2001 From: Josh Matthews Date: Mon, 12 Nov 2018 23:05:02 -0500 Subject: [PATCH 1/2] tmp --- .gitignore | 1 - .taskcluster.yml | 10 +- .travis.yml | 7 +- CONTRIBUTING.md | 4 +- Cargo.lock | 1325 +- Cargo.toml | 6 +- README.md | 24 +- appveyor.yml | 4 +- components/allocator/Cargo.toml | 1 - components/allocator/lib.rs | 54 +- components/atoms/Cargo.toml | 1 - components/atoms/build.rs | 4 +- components/atoms/lib.rs | 2 + components/atoms/static_atoms.txt | 9 - components/bluetooth/Cargo.toml | 12 +- components/bluetooth/lib.rs | 30 +- components/bluetooth/test.rs | 48 +- components/bluetooth_traits/Cargo.toml | 4 +- components/bluetooth_traits/lib.rs | 21 +- components/bluetooth_traits/scanfilter.rs | 8 +- components/canvas/Cargo.toml | 6 +- components/canvas/canvas_data.rs | 675 +- components/canvas/canvas_paint_thread.rs | 231 +- components/canvas/gl_context.rs | 166 +- components/canvas/lib.rs | 17 +- components/canvas/webgl_mode/inprocess.rs | 28 +- components/canvas/webgl_thread.rs | 1236 +- components/canvas_traits/Cargo.toml | 3 +- components/canvas_traits/canvas.rs | 212 +- components/canvas_traits/lib.rs | 19 +- components/canvas_traits/webgl.rs | 166 +- components/canvas_traits/webgl_channel/ipc.rs | 1 + components/canvas_traits/webgl_channel/mod.rs | 6 +- components/channel/Cargo.toml | 1 - components/channel/lib.rs | 43 +- components/compositing/Cargo.toml | 5 +- components/compositing/build.rs | 5 +- components/compositing/compositor.rs | 108 +- components/compositing/compositor_thread.rs | 9 +- components/compositing/gl.rs | 4 +- components/compositing/lib.rs | 29 +- components/compositing/touch.rs | 4 +- components/compositing/windowing.rs | 17 +- components/config/Cargo.toml | 5 +- components/config/lib.rs | 10 + components/config/opts.rs | 49 +- components/config/prefs.rs | 51 +- components/config/tests/opts.rs | 4 +- components/config/tests/prefs.rs | 4 +- components/constellation/Cargo.toml | 7 +- components/constellation/browsingcontext.rs | 2 +- components/constellation/constellation.rs | 537 +- components/constellation/event_loop.rs | 2 +- components/constellation/lib.rs | 40 +- components/constellation/network_listener.rs | 13 +- components/constellation/pipeline.rs | 31 +- components/constellation/session_history.rs | 8 +- components/debugger/Cargo.toml | 1 - components/debugger/lib.rs | 10 +- components/deny_public_fields/Cargo.toml | 1 - components/deny_public_fields/lib.rs | 4 +- components/devtools/Cargo.toml | 8 +- components/devtools/actor.rs | 16 +- .../devtools/actors/browsing_context.rs | 205 - components/devtools/actors/console.rs | 17 +- components/devtools/actors/device.rs | 83 - components/devtools/actors/emulation.rs | 35 - components/devtools/actors/framerate.rs | 4 +- components/devtools/actors/inspector.rs | 24 +- components/devtools/actors/memory.rs | 2 +- components/devtools/actors/network_event.rs | 103 +- components/devtools/actors/object.rs | 2 +- components/devtools/actors/performance.rs | 10 +- components/devtools/actors/profiler.rs | 2 +- components/devtools/actors/root.rs | 40 +- components/devtools/actors/stylesheets.rs | 32 - components/devtools/actors/tab.rs | 179 + components/devtools/actors/thread.rs | 20 +- components/devtools/actors/timeline.rs | 19 +- components/devtools/actors/worker.rs | 2 +- components/devtools/lib.rs | 115 +- components/devtools_traits/Cargo.toml | 4 +- components/devtools_traits/lib.rs | 17 +- components/dom_struct/lib.rs | 6 +- components/domobject_derive/Cargo.toml | 1 - components/domobject_derive/lib.rs | 20 +- components/embedder_traits/Cargo.toml | 7 +- components/embedder_traits/lib.rs | 13 +- components/embedder_traits/resources.rs | 19 +- components/fallible/lib.rs | 2 +- components/geometry/Cargo.toml | 1 - components/geometry/lib.rs | 5 + components/gfx/Cargo.toml | 9 +- components/gfx/font.rs | 32 +- components/gfx/font_cache_thread.rs | 36 +- components/gfx/font_context.rs | 16 +- components/gfx/font_template.rs | 8 +- components/gfx/lib.rs | 59 + .../platform/freetype/android/font_list.rs | 30 +- components/gfx/platform/freetype/font.rs | 21 +- .../gfx/platform/freetype/font_context.rs | 2 +- components/gfx/platform/freetype/font_list.rs | 9 +- .../gfx/platform/freetype/font_template.rs | 5 +- components/gfx/platform/macos/font.rs | 37 +- components/gfx/platform/macos/font_list.rs | 10 +- .../gfx/platform/macos/font_template.rs | 11 +- components/gfx/platform/mod.rs | 8 +- components/gfx/platform/windows/font.rs | 65 +- .../gfx/platform/windows/font_context.rs | 2 - components/gfx/platform/windows/font_list.rs | 6 +- .../gfx/platform/windows/font_template.rs | 5 +- components/gfx/tests/font_context.rs | 20 +- components/gfx/tests/font_template.rs | 14 +- components/gfx/tests/text_util.rs | 4 +- components/gfx/text/glyph.rs | 24 +- components/gfx/text/mod.rs | 4 +- components/gfx/text/shaping/harfbuzz.rs | 66 +- components/gfx/text/shaping/mod.rs | 6 +- components/gfx/text/text_run.rs | 18 +- components/gfx_traits/Cargo.toml | 1 - components/gfx_traits/lib.rs | 3 +- components/hashglobe/src/fake.rs | 4 +- components/hashglobe/src/hash_map.rs | 8 +- components/hashglobe/src/hash_set.rs | 8 +- components/hashglobe/src/table.rs | 2 +- components/jstraceable_derive/Cargo.toml | 1 - components/jstraceable_derive/lib.rs | 9 +- components/layout/Cargo.toml | 1 - components/layout/animation.rs | 29 +- components/layout/block.rs | 73 +- components/layout/construct.rs | 85 +- components/layout/context.rs | 10 +- components/layout/data.rs | 2 +- components/layout/display_list/background.rs | 571 +- components/layout/display_list/border.rs | 202 - components/layout/display_list/builder.rs | 387 +- components/layout/display_list/conversions.rs | 16 +- components/layout/display_list/gradient.rs | 327 - components/layout/display_list/items.rs | 47 +- components/layout/display_list/mod.rs | 2 - .../layout/display_list/webrender_helpers.rs | 118 +- components/layout/flex.rs | 51 +- components/layout/floats.rs | 14 +- components/layout/flow.rs | 70 +- components/layout/flow_list.rs | 32 +- components/layout/flow_ref.rs | 22 +- components/layout/fragment.rs | 163 +- components/layout/generated_content.rs | 29 +- components/layout/incremental.rs | 6 +- components/layout/inline.rs | 59 +- components/layout/layout_debug.rs | 6 +- components/layout/lib.rs | 37 +- components/layout/list_item.rs | 35 +- components/layout/model.rs | 57 +- components/layout/multicol.rs | 37 +- components/layout/opaque_node.rs | 2 +- components/layout/parallel.rs | 25 +- components/layout/persistent_list.rs | 2 +- components/layout/query.rs | 65 +- components/layout/sequential.rs | 38 +- components/layout/table.rs | 47 +- components/layout/table_caption.rs | 22 +- components/layout/table_cell.rs | 33 +- components/layout/table_colgroup.rs | 20 +- components/layout/table_row.rs | 38 +- components/layout/table_rowgroup.rs | 26 +- components/layout/table_wrapper.rs | 54 +- components/layout/tests/size_of.rs | 1 + components/layout/text.rs | 20 +- components/layout/traversal.rs | 56 +- components/layout/wrapper.rs | 6 +- components/layout_thread/Cargo.toml | 4 +- components/layout_thread/dom_wrapper.rs | 60 +- components/layout_thread/lib.rs | 161 +- components/layout_traits/Cargo.toml | 1 - components/layout_traits/lib.rs | 15 +- components/malloc_size_of/Cargo.toml | 10 +- components/malloc_size_of/lib.rs | 90 +- components/malloc_size_of_derive/lib.rs | 3 +- components/metrics/Cargo.toml | 1 - components/metrics/lib.rs | 17 +- components/msg/Cargo.toml | 2 +- components/msg/constellation_msg.rs | 150 +- components/msg/lib.rs | 3 + components/msg/tests/size_of.rs | 1 + components/net/Cargo.toml | 33 +- components/net/blob_loader.rs | 86 +- components/net/connector.rs | 225 +- components/net/cookie.rs | 92 +- components/net/cookie_storage.rs | 88 +- components/net/data_loader.rs | 20 +- components/net/fetch/cors_cache.rs | 115 +- components/net/fetch/methods.rs | 610 +- components/net/filemanager_thread.rs | 374 +- components/net/hosts.rs | 35 +- components/net/hsts.rs | 42 +- components/net/http_cache.rs | 566 +- components/net/http_loader.rs | 1356 +- components/net/image_cache.rs | 186 +- components/net/lib.rs | 44 +- components/net/mime_classifier.rs | 597 +- components/net/resource_thread.rs | 376 +- components/net/storage_thread.rs | 197 +- components/net/subresource_integrity.rs | 59 +- components/net/tests/cookie.rs | 194 +- components/net/tests/cookie_http_state.rs | 2109 ++- components/net/tests/data_loader.rs | 97 +- components/net/tests/fetch.rs | 683 +- components/net/tests/filemanager_thread.rs | 78 +- components/net/tests/hsts.rs | 238 +- components/net/tests/http_cache.rs | 1 + components/net/tests/http_loader.rs | 1196 +- components/net/tests/main.rs | 162 +- components/net/tests/mime_classifier.rs | 449 +- components/net/tests/resource_thread.rs | 59 +- components/net/tests/subresource_integrity.rs | 8 +- components/net/websocket_loader.rs | 275 +- components/net_traits/Cargo.toml | 18 +- components/net_traits/blob_url_store.rs | 4 +- components/net_traits/filemanager_thread.rs | 41 +- components/net_traits/image/base.rs | 69 +- components/net_traits/image_cache.rs | 30 +- components/net_traits/lib.rs | 244 +- components/net_traits/pub_domains.rs | 17 +- components/net_traits/quality.rs | 86 - components/net_traits/request.rs | 82 +- components/net_traits/response.rs | 89 +- components/net_traits/storage_thread.rs | 12 +- components/net_traits/tests/image.rs | 2 + components/net_traits/tests/pub_domains.rs | 7 +- components/net_traits/tests/whitespace.rs | 2 + components/pixels/Cargo.toml | 14 - components/pixels/lib.rs | 84 - components/profile/Cargo.toml | 12 +- components/profile/heartbeats.rs | 6 +- components/profile/lib.rs | 15 + components/profile/mem.rs | 27 +- components/profile/time.rs | 55 +- components/profile/trace_dump.rs | 1 + components/profile_traits/Cargo.toml | 1 - components/profile_traits/ipc.rs | 16 +- components/profile_traits/lib.rs | 5 + components/profile_traits/mem.rs | 18 +- components/profile_traits/time.rs | 13 +- components/rand/Cargo.toml | 1 - components/rand/lib.rs | 6 +- components/range/Cargo.toml | 1 - components/range/lib.rs | 2 + components/remutex/Cargo.toml | 1 - components/remutex/lib.rs | 2 +- components/remutex/tests/smoke.rs | 8 +- components/script/Cargo.toml | 30 +- components/script/body.rs | 48 +- components/script/build.rs | 18 +- components/script/clipboard_provider.rs | 4 +- components/script/devtools.rs | 37 +- components/script/docs/JS-Servos-only-GC.md | 26 +- components/script/document_loader.rs | 13 +- components/script/dom/abstractworker.rs | 8 +- .../script/dom/abstractworkerglobalscope.rs | 22 +- components/script/dom/activation.rs | 18 +- components/script/dom/analysernode.rs | 99 +- components/script/dom/attr.rs | 28 +- components/script/dom/audiobuffer.rs | 142 +- .../script/dom/audiobuffersourcenode.rs | 44 +- components/script/dom/audiocontext.rs | 34 +- components/script/dom/audiodestinationnode.rs | 20 +- components/script/dom/audiolistener.rs | 16 +- components/script/dom/audionode.rs | 24 +- components/script/dom/audioparam.rs | 16 +- .../script/dom/audioscheduledsourcenode.rs | 41 +- components/script/dom/baseaudiocontext.rs | 99 +- components/script/dom/beforeunloadevent.rs | 20 +- components/script/dom/bindings/callback.rs | 20 +- .../script/dom/bindings/codegen/Bindings.conf | 2 +- .../dom/bindings/codegen/CodegenRust.py | 342 +- .../dom/bindings/codegen/Configuration.py | 12 +- components/script/dom/bindings/constant.rs | 5 +- components/script/dom/bindings/conversions.rs | 38 +- components/script/dom/bindings/error.rs | 22 +- .../script/dom/bindings/htmlconstructor.rs | 157 +- components/script/dom/bindings/inheritance.rs | 8 +- components/script/dom/bindings/interface.rs | 29 +- components/script/dom/bindings/iterable.rs | 14 +- components/script/dom/bindings/mozmap.rs | 14 +- components/script/dom/bindings/namespace.rs | 5 +- .../script/dom/bindings/proxyhandler.rs | 12 +- components/script/dom/bindings/refcounted.rs | 23 +- components/script/dom/bindings/reflector.rs | 8 +- components/script/dom/bindings/root.rs | 24 +- .../script/dom/bindings/settings_stack.rs | 9 +- components/script/dom/bindings/str.rs | 2 +- .../script/dom/bindings/structuredclone.rs | 26 +- components/script/dom/bindings/trace.rs | 93 +- components/script/dom/bindings/utils.rs | 61 +- components/script/dom/bindings/weakref.rs | 10 +- components/script/dom/bindings/xmlname.rs | 6 +- components/script/dom/biquadfilternode.rs | 76 +- components/script/dom/blob.rs | 22 +- components/script/dom/bluetooth.rs | 49 +- .../script/dom/bluetoothadvertisingevent.rs | 26 +- .../dom/bluetoothcharacteristicproperties.rs | 11 +- components/script/dom/bluetoothdevice.rs | 47 +- .../script/dom/bluetoothpermissionresult.rs | 34 +- .../dom/bluetoothremotegattcharacteristic.rs | 53 +- .../dom/bluetoothremotegattdescriptor.rs | 38 +- .../script/dom/bluetoothremotegattserver.rs | 27 +- .../script/dom/bluetoothremotegattservice.rs | 26 +- components/script/dom/bluetoothuuid.rs | 12 +- components/script/dom/canvasgradient.rs | 24 +- components/script/dom/canvaspattern.rs | 18 +- .../script/dom/canvasrenderingcontext2d.rs | 301 +- components/script/dom/channelmergernode.rs | 20 +- components/script/dom/characterdata.rs | 36 +- components/script/dom/client.rs | 14 +- components/script/dom/closeevent.rs | 20 +- components/script/dom/comment.rs | 18 +- components/script/dom/compositionevent.rs | 18 +- components/script/dom/console.rs | 8 +- components/script/dom/create.rs | 159 +- components/script/dom/crypto.rs | 18 +- components/script/dom/css.rs | 48 +- components/script/dom/cssconditionrule.rs | 16 +- components/script/dom/cssfontfacerule.rs | 16 +- components/script/dom/cssgroupingrule.rs | 20 +- components/script/dom/cssimportrule.rs | 16 +- components/script/dom/csskeyframerule.rs | 22 +- components/script/dom/csskeyframesrule.rs | 28 +- components/script/dom/cssmediarule.rs | 24 +- components/script/dom/cssnamespacerule.rs | 18 +- components/script/dom/cssrule.rs | 52 +- components/script/dom/cssrulelist.rs | 20 +- components/script/dom/cssstyledeclaration.rs | 35 +- components/script/dom/cssstylerule.rs | 26 +- components/script/dom/cssstylesheet.rs | 22 +- components/script/dom/cssstylevalue.rs | 14 +- components/script/dom/csssupportsrule.rs | 33 +- components/script/dom/cssviewportrule.rs | 16 +- .../script/dom/customelementregistry.rs | 61 +- components/script/dom/customevent.rs | 22 +- .../script/dom/dedicatedworkerglobalscope.rs | 78 +- .../script/dom/dissimilaroriginlocation.rs | 18 +- .../script/dom/dissimilaroriginwindow.rs | 20 +- components/script/dom/document.rs | 544 +- components/script/dom/documentfragment.rs | 28 +- components/script/dom/documenttype.rs | 18 +- components/script/dom/domexception.rs | 14 +- components/script/dom/domimplementation.rs | 59 +- components/script/dom/dommatrix.rs | 26 +- components/script/dom/dommatrixreadonly.rs | 30 +- components/script/dom/domparser.rs | 34 +- components/script/dom/dompoint.rs | 16 +- components/script/dom/dompointreadonly.rs | 12 +- components/script/dom/domquad.rs | 18 +- components/script/dom/domrect.rs | 16 +- components/script/dom/domrectreadonly.rs | 12 +- components/script/dom/domstringmap.rs | 16 +- components/script/dom/domtokenlist.rs | 18 +- components/script/dom/element.rs | 226 +- components/script/dom/errorevent.rs | 24 +- components/script/dom/event.rs | 35 +- components/script/dom/eventsource.rs | 87 +- components/script/dom/eventtarget.rs | 71 +- components/script/dom/extendableevent.rs | 18 +- .../script/dom/extendablemessageevent.rs | 26 +- components/script/dom/file.rs | 23 +- components/script/dom/filelist.rs | 12 +- components/script/dom/filereader.rs | 56 +- components/script/dom/filereadersync.rs | 23 +- components/script/dom/focusevent.rs | 24 +- components/script/dom/formdata.rs | 39 +- components/script/dom/gainnode.rs | 30 +- components/script/dom/gamepad.rs | 28 +- components/script/dom/gamepadbutton.rs | 12 +- components/script/dom/gamepadbuttonlist.rs | 12 +- components/script/dom/gamepadevent.rs | 24 +- components/script/dom/gamepadlist.rs | 14 +- components/script/dom/globalscope.rs | 193 +- components/script/dom/hashchangeevent.rs | 20 +- components/script/dom/headers.rs | 84 +- components/script/dom/history.rs | 32 +- components/script/dom/htmlanchorelement.rs | 50 +- components/script/dom/htmlareaelement.rs | 36 +- components/script/dom/htmlaudioelement.rs | 10 +- components/script/dom/htmlbaseelement.rs | 26 +- components/script/dom/htmlbodyelement.rs | 31 +- components/script/dom/htmlbrelement.rs | 10 +- components/script/dom/htmlbuttonelement.rs | 48 +- components/script/dom/htmlcanvaselement.rs | 125 +- components/script/dom/htmlcollection.rs | 31 +- components/script/dom/htmldataelement.rs | 14 +- components/script/dom/htmldatalistelement.rs | 20 +- components/script/dom/htmldetailselement.rs | 30 +- components/script/dom/htmldialogelement.rs | 22 +- components/script/dom/htmldirectoryelement.rs | 10 +- components/script/dom/htmldivelement.rs | 12 +- components/script/dom/htmldlistelement.rs | 10 +- components/script/dom/htmlelement.rs | 88 +- components/script/dom/htmlembedelement.rs | 10 +- components/script/dom/htmlfieldsetelement.rs | 32 +- components/script/dom/htmlfontelement.rs | 28 +- .../script/dom/htmlformcontrolscollection.rs | 28 +- components/script/dom/htmlformelement.rs | 192 +- components/script/dom/htmlframeelement.rs | 10 +- components/script/dom/htmlframesetelement.rs | 14 +- components/script/dom/htmlheadelement.rs | 26 +- components/script/dom/htmlheadingelement.rs | 10 +- components/script/dom/htmlhrelement.rs | 22 +- components/script/dom/htmlhtmlelement.rs | 10 +- components/script/dom/htmliframeelement.rs | 79 +- components/script/dom/htmlimageelement.rs | 146 +- components/script/dom/htmlinputelement.rs | 102 +- components/script/dom/htmllabelelement.rs | 34 +- components/script/dom/htmllegendelement.rs | 28 +- components/script/dom/htmllielement.rs | 22 +- components/script/dom/htmllinkelement.rs | 42 +- components/script/dom/htmlmapelement.rs | 14 +- components/script/dom/htmlmediaelement.rs | 757 +- components/script/dom/htmlmetaelement.rs | 36 +- components/script/dom/htmlmeterelement.rs | 16 +- components/script/dom/htmlmodelement.rs | 10 +- components/script/dom/htmlobjectelement.rs | 34 +- components/script/dom/htmlolistelement.rs | 10 +- components/script/dom/htmloptgroupelement.rs | 26 +- components/script/dom/htmloptionelement.rs | 44 +- .../script/dom/htmloptionscollection.rs | 42 +- components/script/dom/htmloutputelement.rs | 30 +- components/script/dom/htmlparagraphelement.rs | 10 +- components/script/dom/htmlparamelement.rs | 10 +- components/script/dom/htmlpictureelement.rs | 10 +- components/script/dom/htmlpreelement.rs | 10 +- components/script/dom/htmlprogresselement.rs | 16 +- components/script/dom/htmlquoteelement.rs | 10 +- components/script/dom/htmlscriptelement.rs | 91 +- components/script/dom/htmlselectelement.rs | 58 +- components/script/dom/htmlsourceelement.rs | 44 +- components/script/dom/htmlspanelement.rs | 10 +- components/script/dom/htmlstyleelement.rs | 36 +- .../script/dom/htmltablecaptionelement.rs | 10 +- components/script/dom/htmltablecellelement.rs | 49 +- components/script/dom/htmltablecolelement.rs | 10 +- .../script/dom/htmltabledatacellelement.rs | 43 + components/script/dom/htmltableelement.rs | 50 +- .../script/dom/htmltableheadercellelement.rs | 43 + components/script/dom/htmltablerowelement.rs | 51 +- .../script/dom/htmltablesectionelement.rs | 32 +- components/script/dom/htmltemplateelement.rs | 26 +- components/script/dom/htmltextareaelement.rs | 58 +- components/script/dom/htmltimeelement.rs | 14 +- components/script/dom/htmltitleelement.rs | 24 +- components/script/dom/htmltrackelement.rs | 10 +- components/script/dom/htmlulistelement.rs | 10 +- components/script/dom/htmlunknownelement.rs | 10 +- components/script/dom/htmlvideoelement.rs | 52 +- components/script/dom/imagedata.rs | 54 +- components/script/dom/inputevent.rs | 16 +- components/script/dom/keyboardevent.rs | 793 +- components/script/dom/location.rs | 20 +- components/script/dom/macros.rs | 106 +- components/script/dom/mediaerror.rs | 10 +- components/script/dom/medialist.rs | 18 +- components/script/dom/mediaquerylist.rs | 20 +- components/script/dom/mediaquerylistevent.rs | 24 +- components/script/dom/messageevent.rs | 24 +- components/script/dom/mimetype.rs | 10 +- components/script/dom/mimetypearray.rs | 14 +- components/script/dom/mod.rs | 4 +- components/script/dom/mouseevent.rs | 24 +- components/script/dom/mutationobserver.rs | 32 +- components/script/dom/mutationrecord.rs | 14 +- components/script/dom/namednodemap.rs | 22 +- components/script/dom/navigator.rs | 32 +- components/script/dom/navigatorinfo.rs | 2 +- components/script/dom/node.rs | 147 +- components/script/dom/nodeiterator.rs | 22 +- components/script/dom/nodelist.rs | 14 +- .../script/dom/offlineaudiocompletionevent.rs | 24 +- components/script/dom/offlineaudiocontext.rs | 46 +- components/script/dom/oscillatornode.rs | 26 +- components/script/dom/pagetransitionevent.rs | 20 +- .../script/dom/paintrenderingcontext2d.rs | 42 +- components/script/dom/paintsize.rs | 14 +- .../script/dom/paintworkletglobalscope.rs | 56 +- components/script/dom/pannernode.rs | 36 +- components/script/dom/performance.rs | 43 +- components/script/dom/performanceentry.rs | 14 +- components/script/dom/performanceobserver.rs | 30 +- .../dom/performanceobserverentrylist.rs | 18 +- .../script/dom/performancepainttiming.rs | 12 +- components/script/dom/performancetiming.rs | 14 +- components/script/dom/permissions.rs | 25 +- components/script/dom/permissionstatus.rs | 16 +- components/script/dom/plugin.rs | 10 +- components/script/dom/pluginarray.rs | 14 +- components/script/dom/popstateevent.rs | 24 +- .../script/dom/processinginstruction.rs | 14 +- components/script/dom/progressevent.rs | 20 +- components/script/dom/promise.rs | 24 +- components/script/dom/promisenativehandler.rs | 16 +- .../script/dom/promiserejectionevent.rs | 110 - components/script/dom/radionodelist.rs | 58 +- components/script/dom/range.rs | 51 +- components/script/dom/request.rs | 78 +- components/script/dom/response.rs | 46 +- components/script/dom/screen.rs | 18 +- components/script/dom/serviceworker.rs | 30 +- .../script/dom/serviceworkercontainer.rs | 28 +- .../script/dom/serviceworkerglobalscope.rs | 54 +- .../script/dom/serviceworkerregistration.rs | 22 +- .../script/dom/servoparser/async_html.rs | 54 +- components/script/dom/servoparser/html.rs | 33 +- components/script/dom/servoparser/mod.rs | 109 +- components/script/dom/servoparser/xml.rs | 12 +- components/script/dom/storage.rs | 41 +- components/script/dom/storageevent.rs | 71 +- .../script/dom/stylepropertymapreadonly.rs | 16 +- components/script/dom/stylesheet.rs | 16 +- components/script/dom/stylesheetlist.rs | 14 +- components/script/dom/svgelement.rs | 12 +- components/script/dom/svggraphicselement.rs | 12 +- components/script/dom/svgsvgelement.rs | 24 +- components/script/dom/testbinding.rs | 81 +- components/script/dom/testbindingiterable.rs | 16 +- .../script/dom/testbindingpairiterable.rs | 18 +- components/script/dom/testbindingproxy.rs | 6 +- components/script/dom/testrunner.rs | 14 +- components/script/dom/testworklet.rs | 30 +- .../script/dom/testworkletglobalscope.rs | 16 +- components/script/dom/text.rs | 26 +- components/script/dom/textcontrol.rs | 18 +- components/script/dom/textdecoder.rs | 18 +- components/script/dom/textencoder.rs | 16 +- components/script/dom/timeranges.rs | 176 - components/script/dom/touch.rs | 14 +- components/script/dom/touchevent.rs | 22 +- components/script/dom/touchlist.rs | 12 +- components/script/dom/transitionevent.rs | 24 +- components/script/dom/treewalker.rs | 22 +- components/script/dom/uievent.rs | 20 +- components/script/dom/url.rs | 33 +- components/script/dom/urlhelper.rs | 2 +- components/script/dom/urlsearchparams.rs | 27 +- components/script/dom/userscripts.rs | 10 +- components/script/dom/validation.rs | 2 +- components/script/dom/validitystate.rs | 12 +- components/script/dom/virtualmethods.rs | 182 +- components/script/dom/vr.rs | 32 +- components/script/dom/vrdisplay.rs | 81 +- .../script/dom/vrdisplaycapabilities.rs | 12 +- components/script/dom/vrdisplayevent.rs | 26 +- components/script/dom/vreyeparameters.rs | 16 +- components/script/dom/vrfieldofview.rs | 14 +- components/script/dom/vrframedata.rs | 20 +- components/script/dom/vrpose.rs | 12 +- components/script/dom/vrstageparameters.rs | 16 +- .../script/dom/webgl2renderingcontext.rs | 58 +- .../ext/angleinstancedarrays.rs | 14 +- .../webgl_extensions/ext/extblendminmax.rs | 10 +- .../ext/extcolorbufferhalffloat.rs | 50 - .../ext/extshadertexturelod.rs | 12 +- .../ext/exttexturefilteranisotropic.rs | 12 +- .../script/dom/webgl_extensions/ext/mod.rs | 6 +- .../ext/oeselementindexuint.rs | 12 +- .../ext/oesstandardderivatives.rs | 14 +- .../webgl_extensions/ext/oestexturefloat.rs | 17 +- .../ext/oestexturefloatlinear.rs | 10 +- .../ext/oestexturehalffloat.rs | 19 +- .../ext/oestexturehalffloatlinear.rs | 12 +- .../ext/oesvertexarrayobject.rs | 16 +- .../ext/webglcolorbufferfloat.rs | 50 - .../script/dom/webgl_extensions/extension.rs | 10 +- .../script/dom/webgl_extensions/extensions.rs | 52 +- .../script/dom/webgl_extensions/wrapper.rs | 16 +- .../dom/webgl_validations/tex_image_2d.rs | 10 +- .../script/dom/webgl_validations/types.rs | 4 +- components/script/dom/webglactiveinfo.rs | 12 +- components/script/dom/webglbuffer.rs | 17 +- components/script/dom/webglcontextevent.rs | 22 +- components/script/dom/webglframebuffer.rs | 22 +- components/script/dom/webglobject.rs | 6 +- components/script/dom/webglprogram.rs | 26 +- components/script/dom/webglrenderbuffer.rs | 69 +- .../script/dom/webglrenderingcontext.rs | 268 +- components/script/dom/webglshader.rs | 26 +- .../script/dom/webglshaderprecisionformat.rs | 10 +- components/script/dom/webgltexture.rs | 22 +- components/script/dom/webgluniformlocation.rs | 8 +- .../script/dom/webglvertexarrayobjectoes.rs | 22 +- .../webidls/CanvasRenderingContext2D.webidl | 12 +- components/script/dom/webidls/Document.webidl | 5 +- .../webidls/EXTColorBufferHalfFloat.webidl | 15 - .../dom/webidls/HTMLMediaElement.webidl | 8 +- .../dom/webidls/HTMLTableCellElement.webidl | 7 +- .../webidls/HTMLTableDataCellElement.webidl | 15 + .../webidls/HTMLTableHeaderCellElement.webidl | 15 + .../dom/webidls/HTMLVideoElement.webidl | 4 +- .../dom/webidls/PromiseRejectionEvent.webidl | 16 - .../script/dom/webidls/StorageEvent.webidl | 6 - .../script/dom/webidls/TestBinding.webidl | 2 - .../script/dom/webidls/TimeRanges.webidl | 12 - .../dom/webidls/WEBGLColorBufferFloat.webidl | 14 - components/script/dom/websocket.rs | 55 +- components/script/dom/window.rs | 205 +- components/script/dom/windowproxy.rs | 54 +- components/script/dom/worker.rs | 38 +- components/script/dom/workerglobalscope.rs | 73 +- components/script/dom/workerlocation.rs | 14 +- components/script/dom/workernavigator.rs | 16 +- components/script/dom/worklet.rs | 77 +- components/script/dom/workletglobalscope.rs | 32 +- components/script/dom/xmldocument.rs | 22 +- components/script/dom/xmlhttprequest.rs | 313 +- .../script/dom/xmlhttprequesteventtarget.rs | 4 +- components/script/dom/xmlhttprequestupload.rs | 10 +- components/script/fetch.rs | 47 +- components/script/layout_image.rs | 14 +- components/script/lib.rs | 91 +- components/script/microtask.rs | 32 +- components/script/network_listener.rs | 6 +- components/script/script_runtime.rs | 195 +- components/script/script_thread.rs | 267 +- components/script/serviceworker_manager.rs | 17 +- components/script/serviceworkerjob.rs | 24 +- components/script/stylesheet_loader.rs | 50 +- components/script/task.rs | 6 +- components/script/task_queue.rs | 17 +- .../script/task_source/dom_manipulation.rs | 35 +- components/script/task_source/file_reading.rs | 12 +- .../script/task_source/history_traversal.rs | 6 +- .../script/task_source/media_element.rs | 51 - components/script/task_source/mod.rs | 6 +- components/script/task_source/networking.rs | 8 +- .../task_source/performance_timeline.rs | 12 +- components/script/task_source/remote_event.rs | 8 +- .../script/task_source/user_interaction.rs | 18 +- components/script/task_source/websocket.rs | 8 +- components/script/test.rs | 36 +- components/script/textinput.rs | 207 +- components/script/timers.rs | 22 +- components/script/webdriver_handlers.rs | 95 +- components/script_layout_interface/Cargo.toml | 5 +- components/script_layout_interface/lib.rs | 29 +- components/script_layout_interface/message.rs | 12 +- .../script_layout_interface/reporter.rs | 5 +- components/script_layout_interface/rpc.rs | 2 +- .../script_layout_interface/wrapper_traits.rs | 25 +- .../script_plugins/unrooted_must_root.rs | 6 +- components/script_traits/Cargo.toml | 13 +- components/script_traits/lib.rs | 105 +- components/script_traits/script_msg.rs | 34 +- components/script_traits/webdriver_msg.rs | 27 +- components/selectors/Cargo.toml | 2 +- components/selectors/builder.rs | 29 +- components/selectors/matching.rs | 3 +- components/selectors/parser.rs | 296 +- components/selectors/tree.rs | 4 +- components/servo/Cargo.toml | 5 +- components/servo/lib.rs | 128 +- components/servo_arc/lib.rs | 4 +- components/std_test_override/Cargo.toml | 13 - components/std_test_override/lib.rs | 15 - components/style/Cargo.toml | 2 +- components/style/animation.rs | 276 +- components/style/attr.rs | 4 +- components/style/build.rs | 3 +- components/style/build_gecko.rs | 185 +- components/style/cbindgen.toml | 35 +- components/style/context.rs | 4 +- components/style/counter_style/mod.rs | 7 +- components/style/custom_properties.rs | 395 +- components/style/dom.rs | 4 +- components/style/dom_apis.rs | 96 +- components/style/font_face.rs | 164 +- components/style/font_metrics.rs | 2 +- components/style/gecko/arc_types.rs | 14 +- components/style/gecko/conversions.rs | 109 +- components/style/gecko/data.rs | 7 +- components/style/gecko/global_style_data.rs | 2 +- components/style/gecko/media_features.rs | 37 +- components/style/gecko/media_queries.rs | 23 +- .../style/gecko/non_ts_pseudo_class_list.rs | 1 + components/style/gecko/pseudo_element.rs | 19 +- components/style/gecko/regen_atoms.py | 134 +- components/style/gecko/rules.rs | 192 + components/style/gecko/selector_parser.rs | 4 +- components/style/gecko/snapshot.rs | 2 +- components/style/gecko/snapshot_helpers.rs | 2 +- components/style/gecko/url.rs | 226 +- components/style/gecko/values.rs | 34 +- components/style/gecko/wrapper.rs | 39 +- components/style/gecko_bindings/sugar/mod.rs | 1 + .../sugar/ns_css_shadow_array.rs | 4 +- .../gecko_bindings/sugar/ns_css_value.rs | 65 +- .../sugar/ns_style_auto_array.rs | 2 +- .../gecko_bindings/sugar/ns_style_coord.rs | 30 +- .../style/gecko_bindings/sugar/ns_t_array.rs | 21 +- .../sugar/ns_timing_function.rs | 160 + .../style/gecko_bindings/sugar/refptr.rs | 28 +- .../sugar/style_complex_color.rs | 4 +- components/style/gecko_string_cache/mod.rs | 8 +- .../invalidation/element/element_wrapper.rs | 4 +- .../invalidation/element/invalidation_map.rs | 2 +- .../style/invalidation/element/invalidator.rs | 2 +- .../element/state_and_attributes.rs | 6 +- components/style/invalidation/stylesheets.rs | 6 +- components/style/lib.rs | 15 +- components/style/logical_geometry.rs | 2 +- components/style/matching.rs | 36 +- .../style/media_queries/media_condition.rs | 2 +- .../style/media_queries/media_feature.rs | 6 +- .../media_queries/media_feature_expression.rs | 12 +- components/style/media_queries/media_list.rs | 2 +- components/style/media_queries/media_query.rs | 7 +- components/style/media_queries/mod.rs | 6 +- components/style/properties/cascade.rs | 15 +- components/style/properties/data.py | 3 - .../style/properties/declaration_block.rs | 24 +- components/style/properties/gecko.mako.rs | 207 +- .../helpers/animated_properties.mako.rs | 771 +- .../style/properties/longhands/border.mako.rs | 3 +- .../style/properties/longhands/box.mako.rs | 6 +- .../longhands/inherited_box.mako.rs | 10 +- .../longhands/inherited_svg.mako.rs | 21 +- .../longhands/inherited_text.mako.rs | 2 +- .../properties/longhands/inherited_ui.mako.rs | 2 +- .../style/properties/properties.mako.rs | 261 +- components/style/rule_tree/mod.rs | 27 +- components/style/selector_map.rs | 4 +- components/style/selector_parser.rs | 2 +- components/style/servo/media_queries.rs | 21 +- components/style/servo/restyle_damage.rs | 2 +- components/style/servo/selector_parser.rs | 45 +- components/style/servo/url.rs | 3 - components/style/sharing/mod.rs | 12 +- components/style/style_adjuster.rs | 37 +- components/style/style_resolver.rs | 6 +- components/style/stylesheets/document_rule.rs | 3 +- .../stylesheets/font_feature_values_rule.rs | 9 +- .../style/stylesheets/keyframes_rule.rs | 17 +- components/style/stylesheets/mod.rs | 10 +- .../style/stylesheets/namespace_rule.rs | 2 +- components/style/stylesheets/rule_list.rs | 2 +- components/style/stylesheets/rule_parser.rs | 19 +- .../style/stylesheets/rules_iterator.rs | 2 +- components/style/stylesheets/style_rule.rs | 4 +- components/style/stylesheets/stylesheet.rs | 9 +- components/style/stylesheets/supports_rule.rs | 169 +- components/style/stylesheets/viewport_rule.rs | 4 +- components/style/stylist.rs | 203 +- components/style/traversal.rs | 11 +- components/style/values/animated/effects.rs | 6 +- components/style/values/animated/font.rs | 158 - components/style/values/animated/length.rs | 125 - components/style/values/animated/mod.rs | 131 +- components/style/values/animated/svg.rs | 152 - components/style/values/computed/angle.rs | 94 +- .../style/values/computed/background.rs | 2 +- .../style/values/computed/basic_shape.rs | 5 +- components/style/values/computed/border.rs | 2 +- components/style/values/computed/box.rs | 6 +- components/style/values/computed/color.rs | 2 +- components/style/values/computed/easing.rs | 14 - components/style/values/computed/effects.rs | 6 +- components/style/values/computed/font.rs | 17 +- components/style/values/computed/image.rs | 10 +- components/style/values/computed/length.rs | 217 +- components/style/values/computed/list.rs | 35 +- components/style/values/computed/mod.rs | 68 +- .../style/values/computed/percentage.rs | 3 +- .../style/values/computed/resolution.rs | 2 +- components/style/values/computed/svg.rs | 25 +- components/style/values/computed/text.rs | 4 +- components/style/values/computed/transform.rs | 8 +- components/style/values/computed/ui.rs | 4 +- components/style/values/computed/url.rs | 4 +- .../style/values/generics/background.rs | 31 +- .../style/values/generics/basic_shape.rs | 6 +- components/style/values/generics/counters.rs | 2 +- components/style/values/generics/easing.rs | 113 - components/style/values/generics/grid.rs | 8 +- components/style/values/generics/image.rs | 2 +- components/style/values/generics/length.rs | 54 - components/style/values/generics/mod.rs | 4 +- components/style/values/generics/svg.rs | 57 +- components/style/values/generics/transform.rs | 158 +- components/style/values/generics/ui.rs | 20 +- components/style/values/mod.rs | 16 +- components/style/values/specified/angle.rs | 129 +- .../style/values/specified/basic_shape.rs | 18 +- components/style/values/specified/border.rs | 8 +- components/style/values/specified/box.rs | 102 +- components/style/values/specified/calc.rs | 21 +- components/style/values/specified/color.rs | 2 +- components/style/values/specified/counters.rs | 14 +- components/style/values/specified/easing.rs | 106 - components/style/values/specified/effects.rs | 10 +- components/style/values/specified/font.rs | 88 +- components/style/values/specified/gecko.rs | 2 +- components/style/values/specified/grid.rs | 4 +- components/style/values/specified/image.rs | 66 +- components/style/values/specified/length.rs | 55 +- components/style/values/specified/list.rs | 65 +- components/style/values/specified/mod.rs | 45 +- .../style/values/specified/percentage.rs | 6 +- components/style/values/specified/position.rs | 4 +- .../values/specified/source_size_list.rs | 6 +- components/style/values/specified/svg.rs | 6 +- components/style/values/specified/svg_path.rs | 5 +- components/style/values/specified/text.rs | 63 +- components/style/values/specified/time.rs | 6 +- .../style/values/specified/transform.rs | 133 +- components/style/values/specified/ui.rs | 6 +- components/style/values/specified/url.rs | 4 +- components/style_derive/cg.rs | 11 +- .../style_derive/compute_squared_distance.rs | 2 +- components/style_derive/to_css.rs | 3 +- components/style_traits/Cargo.toml | 2 +- components/style_traits/values.rs | 2 +- components/style_traits/viewport.rs | 4 +- components/url/Cargo.toml | 1 - components/url/lib.rs | 10 +- components/url/origin.rs | 7 + components/webdriver_server/Cargo.toml | 13 +- components/webdriver_server/keys.rs | 263 +- components/webdriver_server/lib.rs | 430 +- components/webvr/Cargo.toml | 1 - components/webvr/lib.rs | 11 +- components/webvr/webvr_thread.rs | 18 +- components/webvr_traits/Cargo.toml | 1 - components/webvr_traits/lib.rs | 40 +- components/webvr_traits/webvr_traits.rs | 4 +- docs/HACKING_QUICKSTART.md | 28 +- docs/components/style.md | 30 +- .../bootstrap-android-and-accept-licences.sh | 17 + etc/ci/buildbot_steps.yml | 26 +- .../performance/download_buildbot_timings.py | 8 +- etc/ci/taskcluster/README.md | 237 + etc/ci/taskcluster/curl-artifact.sh | 23 + etc/ci/taskcluster/decision-task.py | 221 + etc/ci/taskcluster/decisionlib.py | 267 + etc/ci/taskcluster/docker/base.dockerfile | 23 + etc/ci/taskcluster/docker/build.dockerfile | 43 + .../taskcluster/docker/run.dockerfile | 0 etc/ci/taskcluster/mock.py | 45 + etc/doc.servo.org/README.md | 2 +- etc/memory_reports_over_time.py | 0 etc/run_in_headless_android_emulator.py | 6 +- etc/taskcluster/README.md | 249 - etc/taskcluster/decision_task.py | 335 - etc/taskcluster/decisionlib.py | 697 - etc/taskcluster/docker/base.dockerfile | 23 - etc/taskcluster/docker/build.dockerfile | 46 - .../docker/run-android-emulator.dockerfile | 11 - etc/taskcluster/mock.py | 54 - etc/taskcluster/packet.net/.gitignore | 2 - etc/taskcluster/packet.net/README.md | 45 - etc/taskcluster/packet.net/docker-worker.tf | 29 - etc/taskcluster/packet.net/list_devices.py | 47 - etc/taskcluster/packet.net/tc.py | 35 - .../packet.net/terraform_with_vars.py | 43 - etc/taskcluster/windows/.gitignore | 1 - etc/taskcluster/windows/README.md | 88 - etc/taskcluster/windows/base-ami.txt | 1 - etc/taskcluster/windows/bootstrap.ps1 | 54 - etc/taskcluster/windows/build-ami.py | 116 - etc/taskcluster/windows/first-boot.ps1 | 81 - mach.bat | 4 +- ports/libmlservo/Cargo.toml | 20 - ports/libmlservo/src/lib.rs | 492 - ports/libsimpleservo/Cargo.toml | 1 - ports/libsimpleservo/build.rs | 3 + ports/libsimpleservo/src/api.rs | 116 +- ports/libsimpleservo/src/capi.rs | 138 +- ports/libsimpleservo/src/gl_glue.rs | 17 +- ports/libsimpleservo/src/jniapi.rs | 357 +- ports/libsimpleservo/src/lib.rs | 16 +- ports/servo/Cargo.toml | 11 +- ports/servo/browser.rs | 250 +- ports/servo/build.rs | 9 - ports/servo/glutin_app/keyutils.rs | 448 +- ports/servo/glutin_app/window.rs | 136 +- ports/servo/non_android_main.rs | 32 +- ports/servo/platform/macos/count_threads.c | 13 - ports/servo/platform/macos/mod.rs | 32 +- python/servo/bootstrap_commands.py | 99 +- python/servo/build_commands.py | 113 +- python/servo/command_base.py | 12 - python/servo/devenv_commands.py | 17 +- python/servo/package_commands.py | 52 +- python/servo/post_build_commands.py | 6 +- python/servo/testing_commands.py | 24 +- python/servo/util.py | 13 +- python/tidy/servo_tidy/tidy.py | 42 +- python/tidy/servo_tidy_tests/rust_tidy.rs | 1 + python/tidy/servo_tidy_tests/test_tidy.py | 6 + resources/prefs.json | 3 +- resources/servo.css | 33 +- rust-toolchain | 2 +- rustfmt.toml | 3 +- servo-tidy.toml | 18 +- support/android/apk/servoapp/build.gradle | 2 +- .../apk/servoapp/src/main/AndroidManifest.xml | 2 +- .../java/com/mozilla/servo/MainActivity.java | 187 + .../java/org/mozilla/servo/MainActivity.java | 192 - .../src/main/res/layout/activity_main.xml | 4 +- support/android/apk/servoview/build.gradle | 41 +- .../src/googlevr/AndroidManifest.xml | 2 +- .../servoview/src/main/AndroidManifest.xml | 2 +- .../java/com/mozilla/servoview/JNIServo.java | 85 + .../java/com/mozilla/servoview/Servo.java | 216 + .../com/mozilla/servoview/ServoSurface.java | 215 + .../java/com/mozilla/servoview/ServoView.java | 343 + .../java/org/mozilla/servoview/JNIServo.java | 96 - .../java/org/mozilla/servoview/Servo.java | 231 - .../org/mozilla/servoview/ServoSurface.java | 262 - .../java/org/mozilla/servoview/ServoView.java | 365 - .../src/oculusvr/AndroidManifest.xml | 2 +- support/android/openssl.makefile | 4 +- support/linux/gstreamer/gstreamer.sh | 2 +- support/magicleap/.gitignore | 3 - support/magicleap/README.md | 31 - support/magicleap/Servo2D/.vscode/launch.json | 65 - .../magicleap/Servo2D/.vscode/settings.json | 23 - support/magicleap/Servo2D/.vscode/tasks.json | 223 - .../Servo2D/Icon/Model/Model_UFO.fbx | 3466 ----- .../Servo2D/Icon/Model/Model_UFO.kmat | 18 - .../Servo2D/Icon/Model/Model_UFO_Albedo.png | Bin 733 -> 0 bytes .../Icon/Model/Model_UFO_Albedo_Ring.png | Bin 177 -> 0 bytes .../Icon/Portal/InsidePortal_SkySphere.fbx | 509 - .../Icon/Portal/InsidePortal_SkySphere.kmat | 13 - .../Icon/Portal/InsidePortal_SkySphere.png | Bin 6249 -> 0 bytes support/magicleap/Servo2D/Servo2D.mabu | 26 - support/magicleap/Servo2D/Servo2D.mlproject | 5 - support/magicleap/Servo2D/Servo2D.package | 7 - .../Servo2D/code/inc.gen/SceneDescriptor.h | 48 - .../Servo2D/code/inc.gen/scenesGen.h | 34 - support/magicleap/Servo2D/code/inc/Servo2D.h | 121 - .../Servo2D/code/src.gen/SceneDescriptor.cpp | 54 - .../Servo2D/code/src.gen/scenesGen.cpp | 49 - .../magicleap/Servo2D/code/src/Servo2D.cpp | 297 - support/magicleap/Servo2D/code/src/main.cpp | 13 - support/magicleap/Servo2D/code/srcsGen.comp | 3 - support/magicleap/Servo2D/fonts.xml | 19 - support/magicleap/Servo2D/manifest.xml | 20 - .../Servo2D/pipeline/cache/AssetManifest.comp | 1 - .../Servo2D/pipeline/lap/project.json | 36 - support/magicleap/Servo2D/scenes.comp | 3 - .../magicleap/Servo2D/scenes/Servo2D.design | 177 - .../Servo2D/scenes/Servo2D.scene.res.xml | 0 .../Servo2D/scenes/Servo2D.scene.xml | 15 - support/magicleap/fake-ld.sh | 21 - support/magicleap/openssl.sh | 60 - support/magicleap/toolchain.cmake | 1 - support/rust-task_info/Cargo.toml | 1 - support/rust-task_info/build.rs | 2 + support/rust-task_info/src/lib.rs | 1 + support/rust-task_info/src/task_basic_info.rs | 22 +- support/windows/Servo.wxs.mako | 10 +- tests/unit/deny_public_fields/Cargo.toml | 1 - tests/unit/malloc_size_of/Cargo.toml | 1 - tests/unit/malloc_size_of/lib.rs | 6 +- tests/unit/metrics/Cargo.toml | 1 - tests/unit/metrics/interactive_time.rs | 30 +- tests/unit/metrics/lib.rs | 10 + tests/unit/metrics/paint_time.rs | 6 +- tests/unit/profile/Cargo.toml | 4 +- tests/unit/profile/lib.rs | 6 + tests/unit/profile/time.rs | 22 +- tests/unit/script/Cargo.toml | 3 +- tests/unit/script/headers.rs | 20 +- tests/unit/script/htmlareaelement.rs | 140 +- tests/unit/script/htmlimageelement.rs | 136 +- tests/unit/script/lib.rs | 25 +- tests/unit/script/origin.rs | 54 +- tests/unit/script/textinput.rs | 131 +- tests/unit/script/timeranges.rs | 87 - tests/unit/script_plugins/Cargo.toml | 1 - tests/unit/script_plugins/lib.rs | 1 - tests/unit/style/Cargo.toml | 3 +- tests/unit/style/animated_properties.rs | 172 +- tests/unit/style/attr.rs | 28 +- tests/unit/style/custom_properties.rs | 36 +- tests/unit/style/lib.rs | 9 +- tests/unit/style/logical_geometry.rs | 4 +- tests/unit/style/parsing/animation.rs | 26 +- tests/unit/style/parsing/background.rs | 223 +- tests/unit/style/parsing/border.rs | 61 +- tests/unit/style/parsing/effects.rs | 38 +- tests/unit/style/parsing/image.rs | 162 +- tests/unit/style/parsing/inherited_text.rs | 14 +- tests/unit/style/parsing/mod.rs | 94 +- tests/unit/style/parsing/position.rs | 1 + tests/unit/style/parsing/selectors.rs | 11 +- tests/unit/style/parsing/supports.rs | 5 +- .../parsing/transition_timing_function.rs | 61 +- tests/unit/style/properties/mod.rs | 44 +- tests/unit/style/properties/scaffolding.rs | 42 +- tests/unit/style/properties/serialization.rs | 551 +- tests/unit/style/rule_tree/bench.rs | 119 +- tests/unit/style/size_of.rs | 42 +- tests/unit/style/str.rs | 8 +- tests/unit/style/stylesheets.rs | 585 +- tests/unit/style/stylist.rs | 149 +- tests/unit/style/viewport.rs | 600 +- tests/wpt/include.ini | 2 - tests/wpt/metadata/2dcontext/__dir__.ini | 1 - .../2dcontext/imagebitmap/__dir__.ini | 1 - .../canvas-createImageBitmap-resize.html.ini | 16 + ...as-createImageBitmap-video-resize.html.ini | 4 + .../createImageBitmap-bounds.html.ini | 4 + .../createImageBitmap-drawImage.html.ini | 183 + .../createImageBitmap-invalid-args.html.ini | 249 + .../createImageBitmap-origin.sub.html.ini | 22 + .../createImageBitmap-sizeOverflow.html.ini | 17 + .../createImageBitmap-transfer.html.ini | 34 + .../2d.imageData.create2.nonfinite.html.ini | 5 - .../2d.imageData.create2.zero.html.ini | 5 + .../2d.imageData.get.nonfinite.html.ini | 5 - .../2d.imageData.get.zero.html.ini | 5 + .../2d.imageData.put.nonfinite.html.ini | 5 - ...orManaged-convertToBlob-roundtrip.html.ini | 5 - ...vas-colorManaged-toBlob-toDataURL.html.ini | 5 - .../canvas-colorspace-arguments.html.ini | 19 - .../canvas-createImageBitmap-e_srgb.html.ini | 35 - ...reatePutGetImageData-colorManaged.html.ini | 31 - ...canvas-draw-high-bit-depth-images.html.ini | 122 - .../canvas-drawImage-e_srgb.html.ini | 4 - .../canvas-drawImage-offscreenCanvas.html.ini | 13 - .../canvas-getImageData-e_srgb.html.ini | 13 - .../imageData-colorManagedBehavior.html.ini | 4 - .../imageData-colorSpace.html.ini | 19 - ...imagedata-no-color-settings-crash.html.ini | 7 - .../transferFromImageBitmap.html.ini | 25 - tests/wpt/metadata/MANIFEST.json | 11913 +++------------- ...ntrol-expose-headers-parsing.window.js.ini | 1 + tests/wpt/metadata/cors/allow-headers.htm.ini | 15 - tests/wpt/metadata/cors/origin.htm.ini | 16 - .../wpt/metadata/cors/redirect-origin.htm.ini | 24 + .../metadata/cors/redirect-userinfo.htm.ini | 5 + .../wpt/metadata/cors/request-headers.htm.ini | 4 - tests/wpt/metadata/cors/status-async.htm.ini | 37 - .../metadata/cors/status-preflight.htm.ini | 7 - ...-block-in-inline-in-relpos-inline.html.ini | 4 - ...s-inline-in-inline-that-had-block.html.ini | 4 - ...t-to-relpos-inline-that-had-block.html.ini | 4 - .../CSS2/backgrounds/background-043.xht.ini | 1 + .../CSS2/backgrounds/background-048.xht.ini | 4 +- .../CSS2/borders/border-top-width-003.xht.ini | 3 + .../css/CSS2/borders/groove-default.html.ini | 2 + .../css/CSS2/borders/ridge-default.html.ini | 2 + .../clear-on-parent-and-child.html.ini | 3 - .../computed-float-position-absolute.html.ini | 4 - .../CSS2/text/text-indent-percent-001.xht.ini | 3 + .../mix-blend-mode-animation.html.ini | 4 + ...ed-with-transform-and-perspective.html.ini | 2 - .../animationevent-interface.html.ini | 72 - .../css/css-animations/inheritance.html.ini | 49 + .../parsing/animation-delay-computed.html.ini | 10 - .../animation-duration-computed.html.ini | 10 - .../animation-timing-function-valid.html.ini | 11 +- .../css-backgrounds/background-331.html.ini | 2 + .../css-backgrounds/background-333.html.ini | 2 + .../attachment-local-positioning-2.html.ini | 3 - .../attachment-scroll-positioning-1.html.ini | 3 - ...ground-color-body-propagation-005.html.ini | 2 - ...ground-color-body-propagation-006.html.ini | 2 - ...ground-color-root-propagation-001.html.ini | 2 - ...ground-color-root-propagation-002.html.ini | 2 - .../background-size-001.html.ini | 5 + .../border-image-width-005.xht.ini | 3 + .../border-image-width-006.xht.ini | 3 + .../border-image-width-008.html.ini | 2 - ...tioned-multiple-background-images.html.ini | 3 - .../css-flexbox/dynamic-bsize-change.html.ini | 2 - ...lex-minimum-height-flex-items-009.html.ini | 7 - ...lex-minimum-height-flex-items-010.html.ini | 7 - .../font-feature-resolution-001.html.ini | 2 - .../at-font-face-font-matching.html.ini | 102 +- .../font-descriptor-range-reversed.html.ini | 2 - .../font-style-interpolation.html.ini | 2 - .../variations/font-weight-matching.html.ini | 12 +- .../gradient/color-stops-parsing.html.ini | 47 + ...ltiple-position-color-stop-linear.html.ini | 2 + ...ltiple-position-color-stop-radial.html.ini | 2 + .../geometry-border-image-002.https.html.ini | 4 + .../geometry-border-image-003.https.html.ini | 4 + ...-property-interpolation-001.https.html.ini | 2 - ...-property-interpolation-002.https.html.ini | 2 - ...-property-interpolation-003.https.html.ini | 2 - ...-property-interpolation-004.https.html.ini | 2 - ...-property-interpolation-005.https.html.ini | 2 - ...-property-interpolation-006.https.html.ini | 2 - ...-property-interpolation-007.https.html.ini | 2 - ...-property-interpolation-008.https.html.ini | 2 - ...-property-interpolation-009.https.html.ini | 2 - ...-property-interpolation-010.https.html.ini | 2 - ...d-property-invalidation-001.https.html.ini | 2 - ...d-property-invalidation-002.https.html.ini | 2 - ...egistered-property-stylemap.https.html.ini | 2 - ...gistered-property-value-001.https.html.ini | 2 - ...gistered-property-value-002.https.html.ini | 2 - ...gistered-property-value-003.https.html.ini | 2 - ...gistered-property-value-004.https.html.ini | 2 - ...gistered-property-value-005.https.html.ini | 2 - ...gistered-property-value-006.https.html.ini | 2 - ...gistered-property-value-007.https.html.ini | 2 - ...gistered-property-value-008.https.html.ini | 2 - ...gistered-property-value-009.https.html.ini | 2 - ...gistered-property-value-010.https.html.ini | 2 - ...gistered-property-value-011.https.html.ini | 2 - ...gistered-property-value-012.https.html.ini | 2 - ...gistered-property-value-013.https.html.ini | 2 - ...gistered-property-value-014.https.html.ini | 2 - ...gistered-property-value-015.https.html.ini | 2 - ...gistered-property-value-016.https.html.ini | 2 - ...gistered-property-value-017.https.html.ini | 2 - ...gistered-property-value-018.https.html.ini | 2 - .../css/css-text-decor/inheritance.html.ini | 49 + .../hanging-scrollable-001.html.ini | 2 - ...css-text-line-break-ja-cpm-normal.html.ini | 24 +- ...text-line-break-ja-hyphens-strict.html.ini | 12 +- ...css-text-line-break-zh-cpm-normal.html.ini | 24 +- .../css/css-text/inheritance.html.ini | 7 - .../letter-spacing-end-of-line-001.html.ini | 2 - .../letter-spacing-nesting-001.html.ini | 2 - .../overflow-wrap-break-word-004.html.ini | 2 - .../overflow-wrap-break-word-005.html.ini | 2 - .../tab-min-rendered-width-1.html.ini | 2 - ...text-transform-full-size-kana-001.html.ini | 2 - .../white-space/control-chars-000.html.ini | 2 - .../white-space/control-chars-001.html.ini | 2 - .../white-space/control-chars-002.html.ini | 2 - .../white-space/control-chars-003.html.ini | 2 - .../white-space/control-chars-004.html.ini | 2 - .../white-space/control-chars-005.html.ini | 2 - .../white-space/control-chars-006.html.ini | 2 - .../white-space/control-chars-007.html.ini | 2 - .../white-space/control-chars-008.html.ini | 2 - .../white-space/control-chars-00B.html.ini | 2 - .../white-space/control-chars-00D.html.ini | 2 - .../white-space/control-chars-00E.html.ini | 2 - .../white-space/control-chars-00F.html.ini | 2 - .../white-space/control-chars-010.html.ini | 2 - .../white-space/control-chars-011.html.ini | 2 - .../white-space/control-chars-012.html.ini | 2 - .../white-space/control-chars-013.html.ini | 2 - .../white-space/control-chars-014.html.ini | 2 - .../white-space/control-chars-015.html.ini | 2 - .../white-space/control-chars-016.html.ini | 2 - .../white-space/control-chars-017.html.ini | 2 - .../white-space/control-chars-018.html.ini | 2 - .../white-space/control-chars-019.html.ini | 2 - .../white-space/control-chars-01A.html.ini | 2 - .../white-space/control-chars-01B.html.ini | 2 - .../white-space/control-chars-01C.html.ini | 2 - .../white-space/control-chars-01D.html.ini | 2 - .../white-space/control-chars-01E.html.ini | 2 - .../white-space/control-chars-01F.html.ini | 2 - .../white-space/control-chars-07F.html.ini | 2 - .../white-space/control-chars-080.html.ini | 2 - .../white-space/control-chars-081.html.ini | 2 - .../white-space/control-chars-082.html.ini | 2 - .../white-space/control-chars-083.html.ini | 2 - .../white-space/control-chars-084.html.ini | 2 - .../white-space/control-chars-085.html.ini | 2 - .../white-space/control-chars-086.html.ini | 2 - .../white-space/control-chars-087.html.ini | 2 - .../white-space/control-chars-088.html.ini | 2 - .../white-space/control-chars-089.html.ini | 2 - .../white-space/control-chars-08A.html.ini | 2 - .../white-space/control-chars-08B.html.ini | 2 - .../white-space/control-chars-08C.html.ini | 2 - .../white-space/control-chars-08D.html.ini | 2 - .../white-space/control-chars-08E.html.ini | 2 - .../white-space/control-chars-08F.html.ini | 2 - .../white-space/control-chars-090.html.ini | 2 - .../white-space/control-chars-091.html.ini | 2 - .../white-space/control-chars-092.html.ini | 2 - .../white-space/control-chars-093.html.ini | 2 - .../white-space/control-chars-094.html.ini | 2 - .../white-space/control-chars-095.html.ini | 2 - .../white-space/control-chars-096.html.ini | 2 - .../white-space/control-chars-097.html.ini | 2 - .../white-space/control-chars-098.html.ini | 2 - .../white-space/control-chars-099.html.ini | 2 - .../white-space/control-chars-09A.html.ini | 2 - .../white-space/control-chars-09B.html.ini | 2 - .../white-space/control-chars-09C.html.ini | 2 - .../white-space/control-chars-09D.html.ini | 2 - .../white-space/control-chars-09E.html.ini | 2 - .../white-space/control-chars-09F.html.ini | 2 - ...ine-edge-white-space-collapse-001.html.ini | 2 - ...ine-edge-white-space-collapse-002.html.ini | 2 - .../trailing-ideographic-space-001.html.ini | 2 - .../trailing-ideographic-space-002.html.ini | 2 - .../trailing-ideographic-space-004.html.ini | 2 - .../white-space-empty-text-sibling.html.ini | 2 - ...pace-pre-wrap-trailing-spaces-001.html.ini | 2 - ...pace-pre-wrap-trailing-spaces-002.html.ini | 2 - ...pace-pre-wrap-trailing-spaces-003.html.ini | 2 - .../word-break-break-all-010.html.ini | 2 - .../word-break-break-all-011.html.ini | 2 - .../word-break-keep-all-005.html.ini | 2 - .../animation/list-interpolation.html.ini | 67 - .../animation/matrix-interpolation.html.ini | 4 - ...nsforms-3d-on-anonymous-block-001.html.ini | 2 - .../dynamic-fixed-pos-cb-change.html.ini | 2 - .../css/css-transforms/inheritance.html.ini | 10 - .../transform-table-006.html.ini | 3 - .../css/css-transitions/inheritance.html.ini | 25 + .../transition-duration-computed.html.ini | 10 - .../transition-timing-function-valid.html.ini | 11 +- .../properties-value-001.html.ini | 814 +- .../properties-value-003.html.ini | 90 +- .../properties-value-implicit-001.html.ini | 26 +- .../properties-value-inherit-002.html.ini | 114 +- .../transition-timing-function-001.html.ini | 13 - .../transitionevent-interface.html.ini | 7 - ...nsitions-animatable-properties-01.html.ini | 46 +- .../metadata/css/css-ui/inheritance.html.ini | 4 - .../css/cssom-view/CaretPosition-001.html.ini | 4 - .../cssom-view/elementFromPoint-001.html.ini | 4 - ...elementFromPoint-dynamic-anon-box.html.ini | 4 - .../cssom-view/elementFromPosition.html.ini | 6 - .../elementsFromPoint-inline-htb-ltr.html.ini | 4 - .../elementsFromPoint-inline-htb-rtl.html.ini | 4 - .../elementsFromPoint-inline-vlr-ltr.html.ini | 4 - .../elementsFromPoint-inline-vlr-rtl.html.ini | 4 - .../elementsFromPoint-inline-vrl-ltr.html.ini | 4 - .../elementsFromPoint-inline-vrl-rtl.html.ini | 4 - .../elementsFromPoint-invalid-cases.html.ini | 4 + .../getClientRects-br-htb-rtl.html.ini | 4 - .../getClientRects-br-vlr-ltr.html.ini | 4 - .../getClientRects-br-vlr-rtl.html.ini | 4 - .../getClientRects-br-vrl-ltr.html.ini | 4 - .../getClientRects-br-vrl-rtl.html.ini | 4 - .../css/cssom-view/interfaces.html.ini | 12 - .../cssom-view/offsetTopLeftInline.html.ini | 2 - .../css/cssom-view/screenLeftTop.html.ini | 7 - .../scroll-behavior-smooth.html.ini | 3 + .../parsing/backdrop-filter-computed.html.ini | 85 - .../backdrop-filter-parsing-valid.html.ini | 112 - .../parsing/filter-computed.html.ini | 85 - .../parsing/filter-parsing-valid.html.ini | 27 - .../css/selectors/invalidation/where.html.ini | 16 - .../custom-elements/builtin-coverage.html.ini | 5 + .../dom/events/shadow-relatedTarget.html.ini | 4 - .../dom/nodes/Node-insertBefore.html.ini | 4 - .../dom/nodes/Node-replaceChild.html.ini | 7 - ...r-parseFromString-xml-parsererror.html.ini | 52 - .../metadata/encoding/idlharness.any.js.ini | 10 + .../encoding/single-byte-decoder.html.ini | 71 +- .../encoding/streams/backpressure.any.js.ini | 8 +- .../streams/decode-attributes.any.js.ini | 8 +- .../streams/decode-bad-chunks.any.js.ini | 4 +- .../streams/decode-ignore-bom.any.js.ini | 4 +- .../decode-incomplete-input.any.js.ini | 3 +- .../streams/decode-non-utf8.any.js.ini | 3 +- .../streams/decode-split-character.any.js.ini | 3 +- .../encoding/streams/decode-utf8.any.js.ini | 3 +- .../streams/encode-bad-chunks.any.js.ini | 4 +- .../encoding/streams/encode-utf8.any.js.ini | 4 +- .../readable-writable-properties.any.js.ini | 6 +- .../eventsource-cross-origin.htm.ini | 9 + .../format-mime-trailing-semicolon.htm.ini | 4 - .../fetch/api/abort/general.any.js.ini | 12 +- .../basic/header-value-combining.any.js.ini | 40 +- .../basic/header-value-null-byte.any.js.ini | 3 +- .../api/basic/stream-safe-creation.any.js.ini | 3 +- .../api/cors/cors-cookies-redirect.any.js.ini | 4 + .../fetch/api/cors/cors-redirect.any.js.ini | 60 + tests/wpt/metadata/fetch/api/idl.any.js.ini | 1 + .../redirect-empty-location.any.js.ini | 6 + .../api/redirect/redirect-origin.any.js.ini | 33 + .../fetch/api/request/request-error.html.ini | 2 + .../request/request-init-stream.any.js.ini | 3 +- .../api/response/response-consume.html.ini | 4 +- .../response/response-from-stream.any.js.ini | 3 - ...json-parser-breaker.tentative.sub.html.ini | 82 - .../idlharness.tentative.any.js.ini | 10 +- .../fetch-in-iframe.html.ini | 1 + .../fetch.any.js.ini | 7 +- .../fetch/data-urls/processing.any.js.ini | 84 +- .../fetch/nosniff/importscripts.html.ini | 5 - .../nosniff/parsing-nosniff.window.js.ini | 13 - .../metadata/fetch/nosniff/script.html.ini | 4 - .../fetch/nosniff/stylesheet.html.ini | 6 - .../report.tentative.https.sub.html.ini | 2 + .../metadata/hr-time/idlharness.any.js.ini | 9 +- .../scroll-restoration-order.html.ini | 4 - .../traverse_the_history_1.html.ini | 4 - .../traverse_the_history_3.html.ini | 4 - ...se_the_history_write_after_load_2.html.ini | 5 - ...averse_the_history_write_onload_2.html.ini | 4 - ...-protocol-setter-non-broken-weird.html.ini | 7 +- ...cation-protocol-setter-non-broken.html.ini | 7 +- .../no-browsing-context.window.js.ini | 34 - ...n_term_nesting_level_nonzero.window.js.ini | 10 - ...en-features-tokenization-noopener.html.ini | 3 - .../window-properties.https.html.ini | 12 - ...s-origin-nested-browsing-contexts.html.ini | 1 - .../getter.html.ini | 66 +- .../wpt/metadata/html/dom/historical.html.ini | 6 + .../html/dom/interfaces.https.html.ini | 162 +- .../flow-content-0/form-margin-quirk.html.ini | 4 - ...sformed-tbody-tr-collapsed-border.html.ini | 2 - .../legend-block-margins-2.html.ini | 2 - .../legend-list-item-numbering.html.ini | 2 - .../select-1-block-size.html.ini | 2 - .../select-1-line-height.html.ini | 2 - .../the-select-element/select-empty.html.ini | 2 - .../link-style-error-01.html.ini | 36 - .../link-style-error-limited-quirks.html.ini | 37 - .../link-style-error-quirks.html.ini | 31 - .../load-events-networkState.html.ini | 4 - ...lection-invoke-insert-into-iframe.html.ini | 4 - ...lection-invoke-pause-networkState.html.ini | 4 - ...remove-from-document-networkState.html.ini | 4 - .../mime-types/canPlayType.html.ini | 46 +- .../currentTime.html.ini | 15 + .../seeking/seek-to-currentTime.html.ini | 3 +- .../seeking/seek-to-max-value.htm.ini | 3 +- .../seeking/seek-to-negative-time.htm.ini | 3 +- .../the-iframe-element/iframe-nosrc.html.ini | 4 - ...e-with-quick-attach-svg.tentative.html.ini | 4 - .../viewport-change.html.ini | 19 +- .../non-active-document.html.ini | 10 - ...-a-sizes-attribute-standards-mode.html.ini | 1 - .../update-the-source-set.html.ini | 3 - .../form-autocomplete.html.ini | 15 - .../html/semantics/interfaces.html.ini | 13 + .../activation-behavior.window.js.ini | 5 + .../execution-timing/077.html.ini | 6 + .../dynamic-imports-credentials.sub.html.ini | 4 - .../opening-the-input-stream/001.html.ini | 4 + .../opening-the-input-stream/005.html.ini | 4 + .../opening-the-input-stream/008.html.ini | 4 + .../009.https.html.ini | 17 + ...ception-vs-return-origin.sub.window.js.ini | 4 +- .../document.open-02.html.ini | 7 + .../document.open-03.html.ini | 4 + .../event-listeners.window.js.ini | 6 + .../quirks.window.js.ini | 11 +- .../readiness.window.js.ini | 4 + .../tasks.window.js.ini | 6 + .../url-fragment.window.js.ini | 4 + .../queue-microtask-exceptions.any.js.ini | 9 +- .../queue-microtask.any.js.ini | 10 +- .../event-handler-all-global-events.html.ini | 127 +- .../allow-crossorigin.html.ini | 4 + .../disallow-crossorigin.html.ini | 5 - ...ejection-events-attached-in-event.html.ini | 4 + ...-rejection-events.dedicatedworker.html.ini | 36 +- .../promise-rejection-events.html.ini | 54 + .../idlharness.any.js.ini | 1 + .../webtiming-resolution.any.js.ini | 8 +- .../table-cell-width-calculation.html.ini | 21 - .../quirks/unitless-length/no-quirks.html.ini | 283 + .../quirks/unitless-length/quirks.html.ini | 283 + .../external-import-stylesheet.html.ini | 4 - .../internal-import-stylesheet.html.ini | 4 - .../child-css/processing-instruction.html.ini | 5 - .../external-import-stylesheet.html.ini | 5 - .../font-face/external-stylesheet.html.ini | 4 - .../internal-import-stylesheet.html.ini | 5 - .../font-face/internal-stylesheet.html.ini | 4 - .../font-face/processing-instruction.html.ini | 5 - .../image/external-import-stylesheet.html.ini | 5 - .../image/external-stylesheet.html.ini | 5 - .../image/inline-style.html.ini | 5 - .../image/internal-import-stylesheet.html.ini | 5 - .../image/internal-stylesheet.html.ini | 5 - .../image/presentation-attribute.html.ini | 4 - .../image/processing-instruction.html.ini | 5 - .../svg/external-stylesheet.html.ini | 8 - .../css-integration/svg/inline-style.html.ini | 8 - .../svg/internal-stylesheet.html.ini | 8 - .../svg/presentation-attribute.html.ini | 8 - .../svg/processing-instruction.html.ini | 8 - .../multiple-headers-and-values.html.ini | 5 - .../multiple-headers-combined.html.ini | 5 - .../multiple-headers-one-invalid.html.ini | 5 - ...ultiple-headers-one-unknown-token.html.ini | 5 - .../generic/multiple-headers.html.ini | 5 - .../touch-events/idlharness.window.js.ini | 3 - .../url/a-element-origin-xhtml.xhtml.ini | 12 + .../metadata/url/a-element-origin.html.ini | 13 + .../metadata/url/a-element-xhtml.xhtml.ini | 102 +- tests/wpt/metadata/url/a-element.html.ini | 102 +- tests/wpt/metadata/url/failure.html.ini | 115 +- .../wpt/metadata/url/url-constructor.html.ini | 102 +- tests/wpt/metadata/url/url-origin.html.ini | 2 +- tests/wpt/metadata/url/url-setters.html.ini | 162 +- .../metadata/url/urlencoded-parser.any.js.ini | 27 + .../wasm/jsapi/constructor/compile.any.js.ini | 12 - .../jsapi/constructor/instantiate.any.js.ini | 18 - .../wasm/jsapi/global/constructor.any.js.ini | 6 - .../jsapi/global/value-get-set.any.js.ini | 207 - .../wasm/jsapi/global/valueOf.any.js.ini | 6 - .../metadata/wasm/jsapi/idlharness.any.js.ini | 207 - .../metadata/wasm/jsapi/table/grow.any.js.ini | 6 - .../identity-not-preserved.html.ini | 2 +- .../wpt/metadata/wasm/webapi/abort.any.js.ini | 27 - .../wpt/metadata/wasm/webapi/body.any.js.ini | 37 - .../wasm/webapi/contenttype.any.js.ini | 133 - .../wasm/webapi/empty-body.any.js.ini | 61 - .../wasm/webapi/idlharness.any.js.ini | 39 - ...nstantiateStreaming-bad-imports.any.js.ini | 189 - .../webapi/instantiateStreaming.any.js.ini | 61 - .../wasm/webapi/invalid-args.any.js.ini | 277 - .../wasm/webapi/invalid-code.any.js.ini | 25 - .../wasm/webapi/origin.sub.any.js.ini | 37 - .../wasm/webapi/rejected-arg.any.js.ini | 26 - .../metadata/wasm/webapi/status.any.js.ini | 109 - .../realtimeanalyser-fft-scaling.html.ini | 72 - .../audiobuffersource-multi-channels.html.ini | 2 +- .../audiobuffersource-start.html.ini | 15 +- .../buffer-resampling.html.ini | 8 +- .../note-grain-on-play.html.ini | 17 +- .../note-grain-on-timing.html.ini | 17 +- .../sample-accurate-scheduling.html.ini | 10 + .../audiocontextoptions.html.ini | 2 +- .../audionode-channel-rules.html.ini | 19 +- .../audionode-disconnect.html.ini | 2 +- ...stmessage-sharedarraybuffer.https.html.ini | 4 - ...etnode-output-channel-count.https.html.ini | 3 +- .../biquad-allpass.html.ini | 10 + .../biquad-automation.html.ini | 40 +- .../biquad-highpass.html.ini | 10 + .../biquad-highshelf.html.ini | 10 + .../biquad-lowpass.html.ini | 10 + .../biquad-lowshelf.html.ini | 10 + .../biquad-notch.html.ini | 10 + .../biquad-peaking.html.ini | 10 + .../biquad-tail.html.ini | 2 + .../cors-check.https.html.ini | 4 - .../no-cors.https.html.ini | 4 - .../panner-equalpower.html.ini | 2 +- .../Create-Secure-extensions-empty.any.js.ini | 12 - .../metadata/websockets/basic-auth.any.js.ini | 16 +- .../webstorage/event_constructor.html.ini | 4 - .../importscripts_mime.tentative.any.js.ini | 8 +- .../dedicated-worker-import-csp.html.ini | 2 +- .../dedicated-worker-import-failure.html.ini | 1 + ...icated-worker-options-credentials.html.ini | 91 +- .../metadata/workers/name-property.html.ini | 2 +- .../interface-objects/001.worker.js.ini | 9 +- .../semantics/multiple-workers/005.html.ini | 1 + .../xhr/access-control-and-redirects.htm.ini | 5 + ...ess-control-origin-header-data-url.htm.ini | 5 + .../allow-lists-starting-with-comma.htm.ini | 4 - .../xhr/getallresponseheaders.htm.ini | 9 - .../getresponseheader-chunked-trailer.htm.ini | 3 +- .../metadata/xhr/getresponseheader.any.js.ini | 36 - .../xhr/headers-normalize-response.htm.ini | 6 - .../xhr/overridemimetype-blob.html.ini | 42 - .../preserve-ua-header-on-redirect.htm.ini | 5 + .../xhr/responsexml-media-type.htm.ini | 4 - .../metadata/xhr/send-accept-language.htm.ini | 5 + .../xhr/send-content-type-charset.htm.ini | 15 +- .../xhr/send-data-unexpected-tostring.htm.ini | 3 - .../xhr/send-redirect-no-location.htm.ini | 13 - ...setrequestheader-allow-empty-value.htm.ini | 11 + ...stheader-allow-whitespace-in-value.htm.ini | 14 + .../setrequestheader-case-insensitive.htm.ini | 3 - .../setrequestheader-combining.window.js.ini | 4 - .../xhr/setrequestheader-content-type.htm.ini | 66 + .../setrequestheader-header-allowed.htm.ini | 26 +- tests/wpt/metadata/xhr/status-async.htm.ini | 82 - tests/wpt/metadata/xhr/status-basic.htm.ini | 82 - tests/wpt/metadata/xhr/status-error.htm.ini | 13 - tests/wpt/mozilla/meta/MANIFEST.json | 36 +- .../meta/css/border_black_ridge_a.html.ini | 3 + .../meta/css/border_black_ridge_b.html.ini | 3 + .../meta/css/text_node_opacity.html.ini | 2 - .../mozilla/meta/mozilla/scrollBy.html.ini | 4 - .../mozilla/tests/css/transform_skew_ref.html | 6 +- .../mozilla/tests/mozilla/collections.html | 4 +- .../wpt/mozilla/tests/mozilla/interfaces.html | 4 +- .../tests/mozilla/interfaces.worker.js | 1 - .../tests/mozilla/range_request_file_url.html | 121 - .../mozilla/tests/mozilla/resources/range.txt | 199 - .../tests/mozilla/resources/range_small.txt | 1 - .../web-platform-tests/.azure-pipelines.yml | 85 - tests/wpt/web-platform-tests/.pyup.yml | 23 +- tests/wpt/web-platform-tests/.taskcluster.yml | 136 +- tests/wpt/web-platform-tests/.travis.yml | 64 +- .../drawimage_svg_image_1.html | 57 +- .../createImageBitmap-blob-invalidtype.html | 27 - .../createImageBitmap-invalid-args.html | 26 +- .../wide-gamut-canvas/ImageData-fidelity.html | 126 - ...-colorManaged-convertToBlob-roundtrip.html | 149 - .../canvas-colorManaged-toBlob-toDataURL.html | 145 - .../canvas-colorspace-arguments.html | 48 - .../canvas-createImageBitmap-e_srgb.html | 579 - ...as-createPutGetImageData-colorManaged.html | 142 - .../canvas-draw-high-bit-depth-images.html | 109 - .../canvas-drawImage-e_srgb.html | 53 - .../canvas-drawImage-offscreenCanvas.html | 176 - .../canvas-getImageData-e_srgb.html | 96 - .../imageData-colorManagedBehavior.html | 364 - .../imageData-colorSpace.html | 71 - .../imagedata-no-color-settings-crash.html | 26 - .../pattern-semitransparent-p3d65.png | Bin 5912 -> 0 bytes .../pattern-semitransparent-rec2020.png | Bin 6136 -> 0 bytes .../pattern-semitransparent-srgb.png | Bin 5319 -> 0 bytes .../resources/pattern-srgb-fullcolor.ogv | Bin 3710 -> 0 bytes .../resources/pattern-srgb-transparent.bmp | Bin 1738 -> 0 bytes .../resources/pattern-srgb-transparent.ico | Bin 1742 -> 0 bytes .../resources/pattern-srgb-transparent.png | Bin 5319 -> 0 bytes .../resources/pattern-srgb-transparent.webp | Bin 252 -> 0 bytes .../resources/pattern-srgb.bmp | Bin 1738 -> 0 bytes .../resources/pattern-srgb.gif | Bin 117 -> 0 bytes .../resources/pattern-srgb.ico | Bin 1742 -> 0 bytes .../resources/pattern-srgb.jpg | Bin 898 -> 0 bytes .../resources/pattern-srgb.png | Bin 163 -> 0 bytes .../resources/pattern-srgb.svg | 6 - .../resources/pattern-srgb.webp | Bin 208 -> 0 bytes .../png-16bit/2x2_16bit_AdobeRGB_opaque.png | Bin 3164 -> 0 bytes .../2x2_16bit_AdobeRGB_transparent.png | Bin 3175 -> 0 bytes .../png-16bit/2x2_16bit_DisplayP3_opaque.png | Bin 3262 -> 0 bytes .../2x2_16bit_DisplayP3_transparent.png | Bin 3271 -> 0 bytes .../png-16bit/2x2_16bit_ProPhoto_opaque.png | Bin 3338 -> 0 bytes .../2x2_16bit_ProPhoto_transparent.png | Bin 3347 -> 0 bytes .../png-16bit/2x2_16bit_Rec2020_opaque.png | Bin 3144 -> 0 bytes .../2x2_16bit_Rec2020_transparent.png | Bin 3153 -> 0 bytes .../2x2_16bit_interlaced_AdobeRGB_opaque.png | Bin 3165 -> 0 bytes ..._16bit_interlaced_AdobeRGB_transparent.png | Bin 3174 -> 0 bytes .../2x2_16bit_interlaced_DisplayP3_opaque.png | Bin 3265 -> 0 bytes ...16bit_interlaced_DisplayP3_transparent.png | Bin 3272 -> 0 bytes .../2x2_16bit_interlaced_ProPhoto_opaque.png | Bin 3339 -> 0 bytes ..._16bit_interlaced_ProPhoto_transparent.png | Bin 3348 -> 0 bytes .../2x2_16bit_interlaced_Rec2020_opaque.png | Bin 3147 -> 0 bytes ...2_16bit_interlaced_Rec2020_transparent.png | Bin 3153 -> 0 bytes .../2x2_16bit_interlaced_sRGB_opaque.png | Bin 2868 -> 0 bytes .../2x2_16bit_interlaced_sRGB_transparent.png | Bin 2876 -> 0 bytes .../png-16bit/2x2_16bit_sRGB_opaque.png | Bin 2867 -> 0 bytes .../png-16bit/2x2_16bit_sRGB_transparent.png | Bin 2672 -> 0 bytes .../png-16bit/2x2_8bit_AdobeRGB_opaque.png | Bin 3173 -> 0 bytes .../2x2_8bit_AdobeRGB_transparent.png | Bin 3177 -> 0 bytes .../png-16bit/2x2_8bit_DisplayP3_opaque.png | Bin 3250 -> 0 bytes .../2x2_8bit_DisplayP3_transparent.png | Bin 3255 -> 0 bytes .../png-16bit/2x2_8bit_ProPhoto_opaque.png | Bin 3325 -> 0 bytes .../2x2_8bit_ProPhoto_transparent.png | Bin 3331 -> 0 bytes .../png-16bit/2x2_8bit_Rec2020_opaque.png | Bin 3132 -> 0 bytes .../2x2_8bit_Rec2020_transparent.png | Bin 3136 -> 0 bytes .../png-16bit/2x2_8bit_sRGB_opaque.png | Bin 2853 -> 0 bytes .../png-16bit/2x2_8bit_sRGB_transparent.png | Bin 2857 -> 0 bytes .../transferFromImageBitmap.html | 115 - .../IndexedDB/get-databases.any.js | 117 - .../IndexedDB/idbindex-rename-abort.html | 10 +- .../idbobjectstore-rename-abort.html | 10 +- .../reading-autoincrement-common.js | 93 - ...ading-autoincrement-indexes-cursors.any.js | 88 - .../reading-autoincrement-indexes.any.js | 108 - ...reading-autoincrement-store-cursors.any.js | 38 - .../reading-autoincrement-store.any.js | 49 - .../IndexedDB/support-promises.js | 82 +- tests/wpt/web-platform-tests/README.md | 8 +- .../web-platform-tests/WebCryptoAPI/META.yml | 1 + .../WebIDL/current-realm.html | 13 - .../web-platform-tests/accelerometer/META.yml | 1 + .../accname/name_test_case_659-manual.html | 2 +- .../accname/name_test_case_660-manual.html | 2 +- .../web-platform-tests/ambient-light/META.yml | 1 + .../annotation-vocab/META.yml | 1 + .../web-platform-tests/audio-output/META.yml | 1 - .../audio-output/setSinkId.html | 44 - .../audio-output/setSinkId.https.html | 55 +- .../background-fetch/abort.https.window.js | 74 - .../background-fetch/fetch.https.window.js | 131 +- .../background-fetch/get.https.window.js | 1 - ...ontent-and-allowed-schemes.https.window.js | 28 + .../service_workers/sw-abort.js | 23 - .../service_workers/sw-update-ui.js | 15 +- .../background-fetch/service_workers/sw.js | 39 +- .../update-ui.https.window.js | 13 +- .../beacon/beacon-common.sub.js | 210 +- .../beacon/beacon-cors.sub.window.js | 31 +- .../beacon/beacon-error.sub.window.js | 48 - .../beacon/beacon-error.window.js | 48 + .../beacon/beacon-redirect.window.js | 15 +- .../beacon/navigate.iFrame.sub.html | 45 + .../client-hints/image-with-dpr-header.html | 36 - .../client-hints/resources/dpr.py | 24 - .../client-hints/resources/square.png | Bin 18299 -> 0 bytes .../common/get-host-info.sub.js | 25 +- tests/wpt/web-platform-tests/common/large.py | 45 + .../common/performance-timeline-utils.js | 7 - .../common/worklet-reftest.js | 17 +- .../conformance-checkers/.gitignore | 1 - .../conformance-checkers/Makefile | 18 +- .../html/elements/dl/aside-in-dt-novalid.html | 4 + .../input/pattern-asterisk-novalid.html | 4 + .../elements/input/pattern-paren-novalid.html | 4 + .../conformance-checkers/messages.json | 3 + .../304-response-should-update-csp.sub.html | 52 - .../generic/cspro-not-enforced-in-worker.html | 22 - ...ro-not-enforced-in-worker.html.sub.headers | 1 - .../directive-name-case-insensitive.sub.html | 32 - .../only-valid-whitespaces-are-allowed.html | 67 - .../generic/support/304-response.py | 33 - .../generic/support/eval.js | 2 - .../load_img_and_post_result_header.html | 11 - ...mg_and_post_result_header.html.sub.headers | 1 - .../load_img_and_post_result_meta.sub.html | 14 - .../blob-url-self-navigate-inherits.sub.html | 23 - .../support/navigate-self-to-blob.html | 6 - .../navigate-self-to-blob.html.sub.headers | 4 - .../child-navigates-parent-allowed.html | 3 +- .../child-navigates-parent-blocked.sub.html | 9 +- ...form-action-allows-navigate-to-allows.html | 16 + ...-action-allows-navigate-to-allows.sub.html | 16 - ...form-action-allows-navigate-to-blocks.html | 16 + ...-action-allows-navigate-to-blocks.sub.html | 16 - ...form-action-blocks-navigate-to-allows.html | 17 + ...-action-blocks-navigate-to-allows.sub.html | 17 - ...form-action-blocks-navigate-to-blocks.html | 17 + ...-action-blocks-navigate-to-blocks.sub.html | 17 - .../navigate-to/form-blocked.sub.html | 7 - .../form-cross-origin-blocked.sub.html | 7 - .../form-redirected-blocked.sub.html | 8 - .../href-location-blocked.sub.html | 6 - ...ref-location-cross-origin-blocked.sub.html | 6 - .../href-location-redirected-blocked.sub.html | 6 - .../navigate-to/link-click-allowed.html | 1 + .../navigate-to/link-click-blocked.sub.html | 9 +- .../link-click-cross-origin-allowed.sub.html | 1 + .../link-click-cross-origin-blocked.sub.html | 9 +- .../link-click-redirected-allowed.html | 1 + .../link-click-redirected-blocked.sub.html | 8 +- .../navigate-to/meta-refresh-blocked.sub.html | 8 - ...meta-refresh-cross-origin-blocked.sub.html | 8 - .../meta-refresh-redirected-blocked.sub.html | 8 - .../parent-navigates-child-allowed.html | 4 +- .../parent-navigates-child-blocked.html | 9 +- .../spv-only-sent-to-initiator.sub.html | 48 - .../navigate-to/support/delayed_frame.py | 12 - .../support/href_location_navigation.sub.html | 4 - .../support/link_click_navigation.sub.html | 4 - ...redirect_to_post_message_to_frame_owner.py | 2 +- .../support/spv-test-iframe1.sub.html | 19 - .../spv-test-iframe1.sub.html.sub.headers | 4 - .../support/spv-test-iframe2.sub.html | 14 - .../support/spv-test-iframe3.sub.html | 12 - ...d-of-chain-because-of-same-origin.sub.html | 29 - .../allowed-end-of-chain.sub.html | 28 - .../blocked-end-of-chain.sub.html | 29 - .../object-src/object-src-2_1.html | 66 + .../object-src-2_1.html.sub.headers | 6 + .../object-src/object-src-2_2.html | 61 + .../object-src-2_2.html.sub.headers | 6 + .../object-src/object-src-no-url-allowed.html | 18 - ...object-src-no-url-allowed.html.sub.headers | 2 - .../object-src-no-url-allowed.sub.html | 31 + .../object-src/object-src-no-url-blocked.html | 21 - .../object-src-no-url-blocked.sub.html | 27 + .../object-src/object-src-url-allowed.html | 18 - .../object-src-url-allowed.html.sub.headers | 2 - .../object-src-url-allowed.sub.html | 30 + .../object-src/object-src-url-blocked.html | 21 - .../object-src-url-blocked.sub.html | 27 + .../object-src-url-embed-allowed.html | 19 - ...ect-src-url-embed-allowed.html.sub.headers | 2 - .../object-src-url-embed-blocked.html | 22 - .../object-src-url-redirect-allowed.html | 18 - ...-src-url-redirect-allowed.html.sub.headers | 2 - .../object-src-url-redirect-blocked.sub.html | 21 - .../report-cross-origin-no-cookies.sub.html | 30 +- .../report-same-origin-with-cookies.html | 4 - ...-in-report-only-mode-and-sends-report.html | 19 - ...nly-mode-and-sends-report.html.sub.headers | 2 - .../eval-allowed-in-report-only-mode.html | 17 - ...lowed-in-report-only-mode.html.sub.headers | 1 - .../iso-8859-1.html | 20 - .../iso-8859-1.html.sub.headers | 1 - .../iso-8859-3.html | 20 - .../iso-8859-3.html.sub.headers | 1 - .../iso-8859-7.html | 20 - .../iso-8859-7.html.sub.headers | 1 - .../iso-8859-9.html | 20 - .../iso-8859-9.html.sub.headers | 1 - .../utf-8-lone-surrogate.html | 31 - .../utf-8-lone-surrogate.html.sub.headers | 1 - .../hash-always-converted-to-utf-8/utf-8.html | 36 - .../utf-8.html.sub.headers | 1 - .../constructor-required-fields.html | 239 - .../cookies/http-state/chromium-tests.html | 1 + .../test-files/disabled-chromium0022-test | Bin 23 -> 23 bytes .../test-files/disabled-chromium0023-expected | 1 + .../test-files/disabled-chromium0023-test | 1 + .../web-platform-tests/cors/allow-headers.htm | 89 + .../cors/credentials-flag.htm | 5 - tests/wpt/web-platform-tests/cors/origin.htm | 6 - ...s-in-block-in-inline-in-relpos-inline.html | 33 - ...elpos-inline-in-inline-that-had-block.html | 31 - ...acent-to-relpos-inline-that-had-block.html | 29 - .../css/CSS2/borders/border-top-width-003.xht | 2 +- .../css/CSS2/css1/c547-indent-001-ref.xht | 12 +- .../css/CSS2/css1/c547-indent-001.xht | 2 +- .../computed-float-position-absolute.html | 28 - ...ontaining-block-percent-margin-bottom.html | 19 - .../containing-block-percent-margin-left.html | 18 - ...containing-block-percent-margin-right.html | 18 - .../containing-block-percent-margin-top.html | 19 - ...ntaining-block-percent-padding-bottom.html | 18 - ...containing-block-percent-padding-left.html | 18 - ...ontaining-block-percent-padding-right.html | 18 - .../containing-block-percent-padding-top.html | 18 - .../absolute-non-replaced-height-013.html | 9 - .../default-attribute-selector-005.xht | 2 +- .../default-attribute-selector-006.xht | 2 +- .../default-attribute-selector-007.xht | 2 +- .../default-attribute-selector-008.xht | 2 +- .../CSS2/text/text-indent-percent-001-ref.xht | 4 +- .../css/build-css-testsuites.sh | 10 +- .../web-platform-tests/css/css-align/META.yml | 1 - ...KeyframeEffect-getKeyframes.tentative.html | 4 +- .../animationevent-interface.js | 128 - .../css/css-animations/historical.html | 18 - .../parsing/animation-delay-computed.html | 20 - .../parsing/animation-duration-computed.html | 20 - .../animation-timing-function-valid.html | 6 +- .../background-clip-color-repaint.html | 1 + ...background-color-body-propagation-004.html | 10 - ...background-color-body-propagation-005.html | 8 - ...background-color-body-propagation-006.html | 16 - ...background-color-root-propagation-001.html | 10 - ...background-color-root-propagation-002.html | 16 - .../css-backgrounds/background-size-001.html | 2 +- .../border-image-width-008-ref.html | 16 - .../border-image-width-008.html | 20 - .../css/css-conditional/at-supports-040.html | 18 - .../css/css-conditional/at-supports-041.html | 18 - .../css/css-conditional/at-supports-042.html | 18 - .../contain-layout-button-001.html | 20 - .../contain-layout-flexbox-001.html | 20 - .../css-contain/contain-layout-grid-001.html | 20 - .../css-contain/contain-paint-clip-019.html | 38 - .../css-contain/contain-size-button-001.html | 5 +- .../contain-size-fieldset-001.html | 19 - .../css-contain/contain-size-flexbox-001.html | 5 +- .../css-contain/contain-size-grid-001.html | 5 +- .../contain-layout-button-001-ref.html | 19 - .../contain-layout-flexbox-001-ref.html | 16 - .../contain-layout-grid-001-ref.html | 16 - .../reference/contain-paint-clip-019-ref.html | 19 - .../contain-size-button-001-ref.html | 8 +- .../contain-size-fieldset-001-ref.html | 15 - .../contain-size-flexbox-001-ref.html | 8 +- .../reference/contain-size-grid-001-ref.html | 8 +- .../element-replacement-display-contents.html | 2 +- .../element-replacement-display-none.html | 2 +- .../css/css-content/resources/blank.html | 4 + ...splay-contents-shadow-host-whitespace.html | 11 - ...ct-4-option-optgroup-display-none-ref.html | 41 - ...select-4-option-optgroup-display-none.html | 48 - .../css/css-easing/META.yml | 4 - .../cubic-bezier-timing-functions-output.html | 221 - .../step-timing-functions-output.html | 318 - .../step-timing-functions-syntax.html | 34 - .../css/css-exclusions/inheritance.html | 22 - .../css-flexbox/anonymous-flex-item-001.html | 2 +- .../css-flexbox/anonymous-flex-item-002.html | 2 +- .../css-flexbox/anonymous-flex-item-003.html | 2 +- .../css-flexbox/anonymous-flex-item-ref.html | 6 + .../css-flexbox/dynamic-bsize-change-ref.html | 18 - .../css/css-flexbox/dynamic-bsize-change.html | 28 - .../flex-flexitem-percentage-prescation.html | 10 +- .../flex-minimum-height-flex-items-009.html | 62 - .../flex-minimum-height-flex-items-010.html | 64 - .../flex-minimum-height-flex-items-011.xht | 49 - .../css/css-flexbox/flexbox_block.html | 2 +- .../css/css-flexbox/flexbox_empty-ref.html | 2 + .../css-flexbox/flexbox_inline-abspos.html | 2 +- .../css/css-flexbox/flexbox_inline-float.html | 2 +- .../flexbox_order-noninteger-invalid.html | 2 +- .../css/css-flexbox/flexbox_stf-abspos.html | 2 +- .../css/css-flexbox/flexbox_stf-float.html | 2 +- .../css-flexbox/flexbox_stf-inline-block.html | 2 +- .../flexbox_stf-table-caption.html | 2 +- .../css-flexbox/flexbox_stf-table-cell.html | 2 +- .../flexbox_stf-table-row-group.html | 2 +- .../css-flexbox/flexbox_stf-table-row.html | 2 +- .../css/css-flexbox/flexbox_stf-table.html | 2 +- .../flexbox_table-fixed-layout.html | 2 +- .../css-flexbox/flexbox_width-overflow.html | 2 +- .../css-flexbox/percentage-heights-003.html | 38 +- .../css-flexbox/percentage-heights-005.html | 15 - ...ex-flexitem-percentage-prescation-ref.html | 6 +- .../font-feature-resolution-001-ref.html | 356 - .../font-feature-resolution-001.html | 383 - .../font-descriptor-range-reversed-ref.html | 39 - .../font-descriptor-range-reversed.html | 56 - .../web-platform-tests/css/css-grid/META.yml | 1 + .../css/css-grid/abspos/support/grid.css | 6 - .../grid-alignment-style-changes-001.html | 62 - .../grid-alignment-style-changes-002.html | 63 - .../grid-alignment-style-changes-003.html | 63 - .../grid-alignment-style-changes-004.html | 64 - .../grid-alignment-style-changes-005.html | 63 - .../grid-alignment-style-changes-006.html | 64 - .../grid-alignment-style-changes-007.html | 65 - .../grid-alignment-style-changes-008.html | 65 - .../css-grid/alignment/grid-gutters-013.html | 36 - ...plied-if-sizing-cyclic-dependency-003.html | 89 - .../alignment/support/style-change.js | 9 - .../css-grid/grid-definition/support/grid.css | 6 - .../grid-items-relative-offsets-001.html | 95 - .../grid-items-relative-offsets-002.html | 94 - .../css/css-grid/grid-items/support/grid.css | 6 - .../css/css-grid/grid-model/support/grid.css | 6 - .../css/css-images/gradient-crash-ref.html | 1 + .../css/css-images/gradient-crash.html | 2 +- ...iple-position-color-stop-linear-2-ref.html | 5 - ...multiple-position-color-stop-linear-2.html | 9 - ...iple-position-color-stop-radial-2-ref.html | 5 - ...multiple-position-color-stop-radial-2.html | 9 - .../clip-path-content-syling.svg | 6 +- .../clip-path/clip-path-inline-001.html | 31 - .../clip-path/clip-path-inline-002.html | 31 - .../clip-path/clip-path-inline-003.html | 31 - .../css/css-masking/inheritance.html | 38 + .../css/css-masking/inheritance.sub.html | 38 - .../mask-svg-content/mask-negative-scale.svg | 40 - .../mask-svg-content/mask-text-001.svg | 18 - .../mask-svg-content/mask-type-001.svg | 19 - .../mask-svg-content/mask-type-002.svg | 19 - .../mask-svg-content/mask-type-003.svg | 19 - .../reference/mask-green-square-001-ref.svg | 8 - .../reference/mask-negative-scale-001-ref.svg | 15 - .../reference/mask-text-001-ref.svg | 9 - .../css/css-multicol/inheritance.html | 45 - .../multicol-gap-fraction-001.xht | 1 - .../css-multicol/multicol-gap-large-002.xht | 1 - .../multicol-gap-negative-001.xht | 1 - .../css/css-multicol/multicol-inherit-001.xht | 2 +- .../multicol-margin-child-001.xht | 2 +- .../css/css-multicol/multicol-nested-006.html | 19 - .../css/css-multicol/multicol-rule-000.xht | 1 - .../css/css-multicol/multicol-rule-003.xht | 1 - .../css-multicol/multicol-rule-color-001.xht | 1 - .../css-multicol/multicol-rule-dashed-000.xht | 1 - .../css-multicol/multicol-rule-dotted-000.xht | 1 - .../css-multicol/multicol-rule-double-000.xht | 1 - .../multicol-rule-fraction-001.xht | 1 - .../css-multicol/multicol-rule-groove-000.xht | 1 - .../css-multicol/multicol-rule-hidden-000.xht | 1 - .../css-multicol/multicol-rule-none-000.xht | 1 - .../css/css-multicol/multicol-rule-px-001.xht | 1 - .../css-multicol/multicol-rule-ridge-000.xht | 1 - .../multicol-rule-samelength-001.xht | 1 - .../multicol-rule-shorthand-001.xht | 1 - .../multicol-rule-shorthand-2.xht | 2 +- .../css-multicol/multicol-rule-solid-000.xht | 1 - .../multicol-rule-stacking-001.xht | 3 +- .../css-multicol/multicol-shorthand-001.xht | 5 +- .../css/css-multicol/multicol-span-000.xht | 1 - .../css-multicol/multicol-span-all-001.xht | 1 - .../css-multicol/multicol-span-all-002.xht | 3 +- .../multicol-span-all-block-sibling-003.xht | 1 - .../multicol-span-all-margin-001.xht | 2 +- .../multicol-span-all-margin-002.xht | 1 - ...ulticol-span-all-margin-bottom-001-ref.xht | 2 +- .../multicol-span-all-margin-bottom-001.xht | 9 +- .../multicol-span-none-001-ref.xht | 4 +- ...multicol-table-cell-vertical-align-001.xht | 1 - ...multicol-under-vertical-rl-scroll-ref.html | 16 - .../multicol-under-vertical-rl-scroll.html | 12 - .../css/css-overscroll-behavior/META.yml | 3 - .../css-overscroll-behavior/inheritance.html | 22 - ...ered-property-interpolation-001.https.html | 25 - ...ered-property-interpolation-002.https.html | 25 - ...ered-property-interpolation-003.https.html | 25 - ...ered-property-interpolation-004.https.html | 25 - ...ered-property-interpolation-005.https.html | 35 - ...ered-property-interpolation-006.https.html | 25 - ...ered-property-interpolation-007.https.html | 25 - ...ered-property-interpolation-008.https.html | 25 - ...ered-property-interpolation-009.https.html | 25 - ...ered-property-interpolation-010.https.html | 33 - ...tered-property-invalidation-001.https.html | 49 - ...tered-property-invalidation-002.https.html | 52 - .../registered-property-stylemap.https.html | 57 - .../registered-property-type.https.html | 148 + .../registered-property-value-001.https.html | 27 - .../registered-property-value-002.https.html | 31 - .../registered-property-value-003.https.html | 28 - .../registered-property-value-004.https.html | 29 - .../registered-property-value-005.https.html | 29 - .../registered-property-value-006.https.html | 29 - .../registered-property-value-007.https.html | 40 - .../registered-property-value-008.https.html | 29 - .../registered-property-value-009.https.html | 49 - .../registered-property-value-010.https.html | 41 - .../registered-property-value-011.https.html | 29 - .../registered-property-value-012.https.html | 29 - .../registered-property-value-013.https.html | 29 - .../registered-property-value-014.https.html | 29 - .../registered-property-value-015.https.html | 29 - .../registered-property-value-016.https.html | 29 - .../registered-property-value-017.https.html | 29 - .../registered-property-value-018.https.html | 49 - .../css/css-paint-api/resources/utils.js | 59 - .../css/css-position/inheritance.html | 35 - ...position-sticky-child-multicolumn-ref.html | 50 - .../position-sticky-child-multicolumn.html | 55 - .../register-property-syntax-parsing.html | 7 - .../register-property.html | 27 - .../registered-properties-inheritance.html | 14 - .../registered-property-computation.html | 229 +- .../registered-property-cssom.html | 8 +- .../registered-property-initial.html | 62 +- .../resources/utils.js | 94 - .../css-properties-values-api/self-utils.html | 41 - .../typedom.tentative.html | 558 +- .../unit-cycles.html | 38 +- .../var-reference-registered-properties.html | 40 +- .../css/css-regions/inheritance.html | 23 - .../host-context-specificity-001.html | 21 - .../host-context-specificity-002.html | 23 - .../host-context-specificity-003.html | 22 - .../css/css-scoping/host-specificity-003.html | 26 - .../shadow-host-removal-invalidation.html | 21 - .../shadow-reassign-dynamic-003.html | 19 - .../css/css-scoping/slotted-parsing.html | 2 - .../css-scoping/slotted-placeholder-ref.html | 6 - .../css/css-scoping/slotted-placeholder.html | 19 - .../slotted-with-pseudo-element-ref.html | 1 - .../slotted-with-pseudo-element.html | 9 - .../css/css-scroll-anchoring/inheritance.html | 21 - .../text-anchor-in-vertical-rl.html | 30 - .../css/css-scroll-snap/inheritance.html | 39 - .../auto-scrollbar-inline-children.html | 30 - .../values/shape-outside-inset-0010.html | 20 - .../values/support/parsing-utils.js | 21 +- .../css-tables/caption-writing-mode-001.html | 40 - .../hanging-scrollable-001.html | 30 - .../reference/hanging-scrollable-001-ref.html | 6 - .../css/css-text/inheritance.html | 35 - .../letter-spacing-bidi-001.html | 21 - .../letter-spacing-bidi-002.html | 25 - .../letter-spacing-end-of-line-001.html | 21 - .../letter-spacing-nesting-001.html | 20 - .../letter-spacing-nesting-002.html | 20 - .../letter-spacing-bidi-001-ref.html | 14 - .../letter-spacing-bidi-002-ref.html | 14 - .../letter-spacing-end-of-line-001-ref.html | 14 - .../letter-spacing-nesting-001-ref.html | 14 - .../letter-spacing-nesting-002-ref.html | 14 - .../overflow-wrap-break-word-004.html | 36 - .../overflow-wrap-break-word-005.html | 36 - .../tab-min-rendered-width-1-ref.html | 34 - .../tab-size/tab-min-rendered-width-1.html | 27 - .../text-indent-percentage-001-ref.xht | 4 +- .../text-indent-percentage-002-ref.html | 14 - .../text-indent-percentage-001.xht | 6 +- .../text-indent-percentage-002.html | 25 - .../text-indent-percentage-003.html | 25 - .../text-indent-percentage-004.html | 25 - .../text-transform-capitalize-001-ref.html | 7 +- .../text-transform-capitalize-003-ref.html | 7 +- .../text-transform-capitalize-005-ref.html | 7 +- .../text-transform-capitalize-007-ref.html | 7 +- .../text-transform-capitalize-009-ref.html | 7 +- .../text-transform-capitalize-010-ref.html | 7 +- .../text-transform-capitalize-011-ref.html | 7 +- .../text-transform-capitalize-014-ref.html | 7 +- .../text-transform-capitalize-016-ref.html | 7 +- .../text-transform-capitalize-018-ref.html | 7 +- .../text-transform-capitalize-020-ref.html | 7 +- .../text-transform-capitalize-022-ref.html | 5 +- .../text-transform-capitalize-024-ref.html | 5 +- .../text-transform-capitalize-026-ref.html | 6 +- .../text-transform-capitalize-028-ref.html | 5 +- .../text-transform-capitalize-030-ref.html | 5 +- .../text-transform-capitalize-031-ref.html | 2 +- ...text-transform-full-size-kana-001-ref.html | 69 - ...text-transform-full-size-kana-002-ref.html | 225 - .../text-transform-tailoring-001-ref.html | 2 +- .../text-transform-tailoring-002-ref.html | 2 +- .../text-transform-tailoring-002a-ref.html | 2 +- .../text-transform-tailoring-003-ref.html | 2 +- .../text-transform-tailoring-004-ref.html | 2 +- .../text-transform-tailoring-005-ref.html | 2 +- .../text-transform-upperlower-001-ref.html | 7 +- .../text-transform-upperlower-002-ref.html | 7 +- .../text-transform-upperlower-003-ref.html | 5 +- .../text-transform-upperlower-004-ref.html | 5 +- .../text-transform-upperlower-005-ref.html | 5 +- .../text-transform-upperlower-006-ref.html | 5 +- .../text-transform-upperlower-007-ref.html | 5 +- .../text-transform-upperlower-008-ref.html | 5 +- .../text-transform-upperlower-009-ref.html | 5 +- .../text-transform-upperlower-010-ref.html | 5 +- .../text-transform-upperlower-011-ref.html | 5 +- .../text-transform-upperlower-012-ref.html | 5 +- .../text-transform-upperlower-014-ref.html | 5 +- .../text-transform-upperlower-015-ref.html | 5 +- .../text-transform-upperlower-016-ref.html | 5 +- .../text-transform-upperlower-017-ref.html | 5 +- .../text-transform-upperlower-018-ref.html | 5 +- .../text-transform-upperlower-019-ref.html | 5 +- .../text-transform-upperlower-020-ref.html | 7 +- .../text-transform-upperlower-021-ref.html | 7 +- .../text-transform-upperlower-022-ref.html | 3 +- .../text-transform-upperlower-023-ref.html | 3 +- .../text-transform-upperlower-024-ref.html | 3 +- .../text-transform-upperlower-025-ref.html | 3 +- .../text-transform-upperlower-026-ref.html | 3 +- .../text-transform-upperlower-027-ref.html | 3 +- .../text-transform-upperlower-028-ref.html | 5 +- .../text-transform-upperlower-029-ref.html | 5 +- .../text-transform-upperlower-030-ref.html | 5 +- .../text-transform-upperlower-031-ref.html | 3 +- .../text-transform-upperlower-032-ref.html | 2 +- .../text-transform-upperlower-033-ref.html | 2 +- .../text-transform-upperlower-034-ref.html | 2 +- .../text-transform-upperlower-035-ref.html | 2 +- .../text-transform-upperlower-038-ref.html | 2 +- .../text-transform-upperlower-039-ref.html | 2 +- .../text-transform-upperlower-040-ref.html | 2 +- .../text-transform-upperlower-041-ref.html | 2 +- .../text-transform-upperlower-042-ref.html | 2 +- .../text-transform-upperlower-043-ref.html | 2 +- .../text-transform-upperlower-101-ref.html | 5 +- .../text-transform-upperlower-102-ref.html | 3 +- .../text-transform-upperlower-103-ref.html | 3 +- .../text-transform-upperlower-104-ref.html | 3 +- .../text-transform-capitalize-001.html | 7 +- .../text-transform-capitalize-003.html | 7 +- .../text-transform-capitalize-005.html | 7 +- .../text-transform-capitalize-007.html | 7 +- .../text-transform-capitalize-009.html | 7 +- .../text-transform-capitalize-010.html | 7 +- .../text-transform-capitalize-011.html | 7 +- .../text-transform-capitalize-014.html | 7 +- .../text-transform-capitalize-016.html | 7 +- .../text-transform-capitalize-018.html | 7 +- .../text-transform-capitalize-020.html | 7 +- .../text-transform-capitalize-022.html | 5 +- .../text-transform-capitalize-024.html | 5 +- .../text-transform-capitalize-026.html | 6 +- .../text-transform-capitalize-028.html | 5 +- .../text-transform-capitalize-030.html | 5 +- .../text-transform-capitalize-031.html | 2 +- .../text-transform-full-size-kana-001.html | 71 - .../text-transform-full-size-kana-002.html | 227 - .../text-transform-tailoring-001.html | 2 +- .../text-transform-tailoring-002.html | 2 +- .../text-transform-tailoring-002a.html | 2 +- .../text-transform-tailoring-003.html | 2 +- .../text-transform-tailoring-004.html | 2 +- .../text-transform-tailoring-005.html | 2 +- .../text-transform-upperlower-001.html | 7 +- .../text-transform-upperlower-002.html | 7 +- .../text-transform-upperlower-003.html | 5 +- .../text-transform-upperlower-004.html | 5 +- .../text-transform-upperlower-005.html | 5 +- .../text-transform-upperlower-006.html | 5 +- .../text-transform-upperlower-007.html | 5 +- .../text-transform-upperlower-008.html | 5 +- .../text-transform-upperlower-009.html | 5 +- .../text-transform-upperlower-010.html | 5 +- .../text-transform-upperlower-011.html | 5 +- .../text-transform-upperlower-012.html | 5 +- .../text-transform-upperlower-014.html | 5 +- .../text-transform-upperlower-015.html | 5 +- .../text-transform-upperlower-016.html | 5 +- .../text-transform-upperlower-017.html | 5 +- .../text-transform-upperlower-018.html | 5 +- .../text-transform-upperlower-019.html | 5 +- .../text-transform-upperlower-020.html | 7 +- .../text-transform-upperlower-021.html | 7 +- .../text-transform-upperlower-022.html | 3 +- .../text-transform-upperlower-023.html | 3 +- .../text-transform-upperlower-024.html | 3 +- .../text-transform-upperlower-025.html | 3 +- .../text-transform-upperlower-026.html | 3 +- .../text-transform-upperlower-027.html | 3 +- .../text-transform-upperlower-028.html | 5 +- .../text-transform-upperlower-029.html | 5 +- .../text-transform-upperlower-030.html | 5 +- .../text-transform-upperlower-031.html | 3 +- .../text-transform-upperlower-032.html | 2 +- .../text-transform-upperlower-033.html | 2 +- .../text-transform-upperlower-034.html | 2 +- .../text-transform-upperlower-035.html | 2 +- .../text-transform-upperlower-038.html | 2 +- .../text-transform-upperlower-039.html | 2 +- .../text-transform-upperlower-040.html | 2 +- .../text-transform-upperlower-041.html | 2 +- .../text-transform-upperlower-042.html | 2 +- .../text-transform-upperlower-043.html | 2 +- .../text-transform-upperlower-101.html | 5 +- .../text-transform-upperlower-102.html | 3 +- .../text-transform-upperlower-103.html | 3 +- .../text-transform-upperlower-104.html | 3 +- .../white-space/break-spaces-003.html | 28 + .../white-space/control-chars-000.html | 18 - .../white-space/control-chars-001.html | 18 - .../white-space/control-chars-002.html | 18 - .../white-space/control-chars-003.html | 18 - .../white-space/control-chars-004.html | 18 - .../white-space/control-chars-005.html | 18 - .../white-space/control-chars-006.html | 18 - .../white-space/control-chars-007.html | 18 - .../white-space/control-chars-008.html | 18 - .../white-space/control-chars-00B.html | 18 - .../white-space/control-chars-00D.html | 18 - .../white-space/control-chars-00E.html | 18 - .../white-space/control-chars-00F.html | 18 - .../white-space/control-chars-010.html | 18 - .../white-space/control-chars-011.html | 18 - .../white-space/control-chars-012.html | 18 - .../white-space/control-chars-013.html | 18 - .../white-space/control-chars-014.html | 18 - .../white-space/control-chars-015.html | 18 - .../white-space/control-chars-016.html | 18 - .../white-space/control-chars-017.html | 18 - .../white-space/control-chars-018.html | 18 - .../white-space/control-chars-019.html | 18 - .../white-space/control-chars-01A.html | 18 - .../white-space/control-chars-01B.html | 18 - .../white-space/control-chars-01C.html | 18 - .../white-space/control-chars-01D.html | 18 - .../white-space/control-chars-01E.html | 18 - .../white-space/control-chars-01F.html | 18 - .../white-space/control-chars-07F.html | 18 - .../white-space/control-chars-080.html | 18 - .../white-space/control-chars-081.html | 18 - .../white-space/control-chars-082.html | 18 - .../white-space/control-chars-083.html | 18 - .../white-space/control-chars-084.html | 18 - .../white-space/control-chars-085.html | 18 - .../white-space/control-chars-086.html | 18 - .../white-space/control-chars-087.html | 18 - .../white-space/control-chars-088.html | 18 - .../white-space/control-chars-089.html | 18 - .../white-space/control-chars-08A.html | 18 - .../white-space/control-chars-08B.html | 18 - .../white-space/control-chars-08C.html | 18 - .../white-space/control-chars-08D.html | 18 - .../white-space/control-chars-08E.html | 18 - .../white-space/control-chars-08F.html | 18 - .../white-space/control-chars-090.html | 18 - .../white-space/control-chars-091.html | 18 - .../white-space/control-chars-092.html | 18 - .../white-space/control-chars-093.html | 18 - .../white-space/control-chars-094.html | 18 - .../white-space/control-chars-095.html | 18 - .../white-space/control-chars-096.html | 18 - .../white-space/control-chars-097.html | 18 - .../white-space/control-chars-098.html | 18 - .../white-space/control-chars-099.html | 18 - .../white-space/control-chars-09A.html | 18 - .../white-space/control-chars-09B.html | 18 - .../white-space/control-chars-09C.html | 18 - .../white-space/control-chars-09D.html | 18 - .../white-space/control-chars-09E.html | 18 - .../white-space/control-chars-09F.html | 18 - .../line-edge-white-space-collapse-001.html | 40 - .../line-edge-white-space-collapse-002.html | 40 - .../css-text/white-space/pre-wrap-015.html | 32 - .../reference/control-chars-000-ref.html | 6 - ...ine-edge-white-space-collapse-001-ref.html | 23 - ...ine-edge-white-space-collapse-002-ref.html | 24 - .../trailing-ideographic-space-001-ref.html | 7 - .../trailing-ideographic-space-003-ref.html | 11 - .../trailing-ideographic-space-004-ref.html | 11 - ...railing-ideographic-space-alt-003-ref.html | 22 - ...pace-pre-wrap-trailing-spaces-001-ref.html | 18 - ...pace-pre-wrap-trailing-spaces-002-ref.html | 8 - .../textarea-break-spaces-003.html | 39 + .../trailing-ideographic-space-001.html | 14 - .../trailing-ideographic-space-002.html | 14 - .../trailing-ideographic-space-003.html | 26 - .../trailing-ideographic-space-004.html | 26 - .../white-space-empty-text-sibling.html | 11 - ...te-space-pre-wrap-trailing-spaces-001.html | 31 - ...te-space-pre-wrap-trailing-spaces-002.html | 20 - ...te-space-pre-wrap-trailing-spaces-003.html | 27 - .../word-break-break-all-010-ref.html | 16 - .../word-break-break-all-014-ref.html | 6 - .../word-break-break-all-020-ref.html | 21 - .../word-break-keep-all-005-ref.html | 7 - .../word-break/word-break-break-all-010.html | 37 - .../word-break/word-break-break-all-011.html | 36 - .../word-break/word-break-break-all-014.html | 16 - .../word-break/word-break-break-all-020.html | 33 - .../word-break/word-break-keep-all-005.html | 28 - .../word-break/word-break-keep-all-006.html | 33 - .../css/css-timing/META.yml | 4 + .../cubic-bezier-timing-functions-output.html | 221 + .../step-timing-functions-output.html | 141 + .../{css-easing => css-timing}/testcommon.js | 0 .../animation/list-interpolation.html | 140 - .../animation/matrix-interpolation.html | 36 - .../resources/interpolation-testcommon.js | 7 +- .../dynamic-fixed-pos-cb-change-ref.html | 47 - .../dynamic-fixed-pos-cb-change.html | 65 - .../css/css-transforms/inheritance.html | 41 - .../parsing/scale-parsing-valid.html | 2 - .../css-transforms/text-perspective-001.html | 27 - .../parsing/transition-duration-computed.html | 20 - .../transition-timing-function-invalid.html | 2 +- .../transition-timing-function-valid.html | 8 +- .../transition-timing-function-001.html | 8 - .../transitionevent-interface.html | 229 - .../properties/pointer-events.html | 6 +- .../css/css-ui/inheritance.html | 47 - .../css/css-values/vh-support-margin.html | 4 +- .../will-change-abspos-cb-001-ref.html | 24 - .../will-change-abspos-cb-001.html | 30 - .../will-change-abspos-cb-dynamic-001.html | 34 - .../will-change-inherit-dynamic.html | 21 - .../inline-box-border-vlr-001.html | 27 - .../reference/inline-box-border-vlr-001.html | 23 - .../elementsFromPoint-inline-htb-ltr.html | 18 - .../elementsFromPoint-inline-htb-rtl.html | 18 - .../elementsFromPoint-inline-vlr-ltr.html | 18 - .../elementsFromPoint-inline-vlr-rtl.html | 18 - .../elementsFromPoint-inline-vrl-ltr.html | 18 - .../elementsFromPoint-inline-vrl-rtl.html | 18 - .../cssom-view/getClientRects-br-htb-ltr.html | 16 - .../cssom-view/getClientRects-br-htb-rtl.html | 16 - .../cssom-view/getClientRects-br-vlr-ltr.html | 16 - .../cssom-view/getClientRects-br-vlr-rtl.html | 16 - .../cssom-view/getClientRects-br-vrl-ltr.html | 16 - .../cssom-view/getClientRects-br-vrl-rtl.html | 16 - .../css/cssom-view/getClientRects-inline.html | 55 - .../css/cssom-view/inheritance.html | 21 - .../css/cssom-view/offsetTopLeftInline.html | 54 - .../css/cssom-view/screenLeftTop.html | 16 - .../scroll-behavior-smooth-positions.html | 2 +- .../wpt/web-platform-tests/css/cssom/CSS.html | 8 - ...ssstyledeclaration-mutationrecord-002.html | 2 +- ...ssstyledeclaration-mutationrecord-005.html | 16 - .../cssstyledeclaration-setter-attr.html | 18 - .../css/filter-effects/META.yml | 1 - .../filter-effects/filter-scale-001-ref.html | 10 - .../css/filter-effects/filter-scale-001.html | 31 - .../filter-scaling-001-ref.html | 36 - .../filter-effects/filter-scaling-001.html | 47 - .../css/filter-effects/inheritance.html | 25 - .../parsing/backdrop-filter-computed.html | 62 - .../backdrop-filter-parsing-invalid.html | 54 - .../backdrop-filter-parsing-valid.html | 67 - .../parsing/filter-computed.html | 62 - .../parsing/filter-parsing-invalid.html | 9 + .../parsing/filter-parsing-valid.html | 9 - .../web-platform-tests/css/geometry/META.yml | 1 + .../resources/interpolation-testcommon.js | 5 +- .../css/motion/inheritance.html | 25 - .../css/motion/offset-path-serialization.html | 4 - .../parsing/offset-rotate-computed.html | 23 - .../css/reference/blank.html | 3 - .../css/reference/pass_if_two_words.html | 5 - .../selectors/floating-first-letter-05d0.html | 20 - .../selectors/floating-first-letter-feff.html | 17 - .../selectors/floating-first-letter-ref.html | 14 - .../css/selectors/focus-visible-009.html | 2 +- .../css/selectors/invalidation/where.html | 108 - ...placeholder-shown-emptify-placeholder.html | 22 - .../css/support/computed-testcommon.js | 22 - .../web-platform-tests/css/support/grid.css | 6 - .../css/support/inheritance-testcommon.js | 32 - .../css/support/parsing-testcommon.js | 13 +- ...layout-ignored-cases-ib-split-001-ref.html | 76 - ...ain-layout-ignored-cases-ib-split-001.html | 77 - ...-paint-ignored-cases-ib-split-001-ref.html | 76 - ...tain-paint-ignored-cases-ib-split-001.html | 77 - .../contain/contain-size-block-001-ref.html | 7 +- .../contain/contain-size-block-001.html | 2 +- .../contain-size-fieldset-001-ref.html | 1 - .../contain/contain-size-fieldset-001.html | 1 - .../contain-size-fieldset-002-ref.html | 14 +- .../contain/contain-size-fieldset-002.html | 4 +- .../contain-size-inline-block-001-ref.html | 17 +- .../contain-size-inline-block-001.html | 4 +- .../contain-size-inline-flex-001-ref.html | 9 +- .../contain/contain-size-inline-flex-001.html | 6 +- .../contain/reftest.list | 2 - .../flexbox/flexbox-dyn-resize-001-ref.html | 60 - .../flexbox/flexbox-dyn-resize-001.html | 65 - .../flexbox/reftest.list | 3 - .../shapes1/reftest.list | 1 + .../individual-transform-1-ref.html | 90 + .../transforms/individual-transform-1.html | 100 + .../individual-transform-2-ref.html | 30 + .../transforms/individual-transform-2a.html | 32 + .../transforms/individual-transform-2b.html | 32 + .../transforms/individual-transform-2c.html | 32 + .../transforms/individual-transform-2d.html | 31 + .../transforms/individual-transform-2e.html | 31 + .../transforms/reftest.list | 7 + .../calc-background-position-1-ref.html | 2 +- .../values3/calc-background-position-1.html | 2 +- .../values3/calc-background-size-1-ref.html | 2 +- .../values3/calc-background-size-1.html | 2 +- .../values3/support/blue-32x32.png | Bin 110 -> 0 bytes .../web-platform-tests/docs/_admin/index.md | 76 - tests/wpt/web-platform-tests/docs/_config.yml | 2 - .../docs/_includes/svg/octicons/key.svg | 3 - .../docs/_reviewing-tests/email.md | 11 - .../docs/_running-tests/index.md | 6 +- .../docs/_running-tests/safari.md | 12 +- .../docs/_writing-tests/file-names.md | 7 - .../docs/_writing-tests/rendering.md | 4 - .../docs/_writing-tests/testdriver.md | 8 - .../docs/_writing-tests/testharness-api.md | 11 +- tests/wpt/web-platform-tests/docs/index.html | 11 - .../web-platform-tests/docs/introduction.md | 6 - .../Event-dispatch-on-disabled-elements.html | 132 - ...entListener-addEventListener.sub.window.js | 2 +- .../dom/events/shadow-relatedTarget.html | 30 - .../dom/nodes/Node-insertBefore.html | 6 - .../dom/nodes/Node-replaceChild.html | 34 +- .../dom/nodes/pre-insertion-checks.js | 108 - ...arser-parseFromString-xml-parsererror.html | 38 - .../data/insert-list-items-in-table-cells.js | 6 +- .../editing/data/insertorderedlist.js | 17 +- .../encoding/resources/two-boms-utf-16be.html | 2 +- .../encoding/resources/two-boms-utf-16le.html | 2 +- .../eventsource/eventsource-prototype.htm | 2 +- .../layout-animations-disabled-tentative.html | 39 - ...animations-disabled-tentative.html.headers | 1 - .../layout-animations-enabled-tentative.html | 30 - ...lazyload-disabled-image-tentative.sub.html | 61 - ...-disabled-image-tentative.sub.html.headers | 2 - .../lazyload-enabled-image-tentative.sub.html | 45 - ...tribute-on-sanity-check-tentative.sub.html | 48 - .../experimental-features/resources/common.js | 7 - .../resources/lazyload.png | Bin 20819 -> 0 bytes .../vertical-scroll-scrollable-content.html | 16 - .../vertical-scroll-scrollbar-ref.html | 13 - ...bled-frame-no-scroll-manual.tentative.html | 113 - ...l-scroll-disabled-scrollbar-tentative.html | 4 - ...rame-policy-allowed-for-all.https.sub.html | 92 +- ...ame-policy-allowed-for-self.https.sub.html | 116 +- ...ame-policy-allowed-for-some.https.sub.html | 116 +- ...e-policy-disallowed-for-all.https.sub.html | 92 +- ...licy-header-policy-declined.https.sub.html | 65 - ...policy-declined.https.sub.html.sub.headers | 1 - ...-attribute-redirect-on-load.https.sub.html | 5 +- ...by-feature-policy-attribute.https.sub.html | 5 +- ...e-allowed-by-feature-policy.https.sub.html | 7 +- ...ture-default-feature-policy.https.sub.html | 7 +- ...-disabled-by-feature-policy.https.sub.html | 7 +- .../encrypted-media-reporting.https.html | 37 - ...crypted-media-reporting.https.html.headers | 1 - .../generic-sensor-reporting.https.html | 55 - ...eneric-sensor-reporting.https.html.headers | 1 - .../picture-in-picture-reporting.html | 46 - .../picture-in-picture-reporting.html.headers | 1 - .../feature-policy-picture-in-picture.html | 1 - .../feature-policy/resources/featurepolicy.js | 12 +- .../resources/picture-in-picture.js | 19 +- .../serviceworker-intercepted.https.html | 12 +- .../api/basic/header-value-combining.any.js | 22 +- .../api/headers/header-values-normalize.html | 2 +- .../fetch/api/redirect/redirect-count.any.js | 1 - .../fetch-destination-worker-no-load-event.js | 5 +- .../fetch/api/resources/inspect-headers.py | 1 + .../corb/resources/sniffable-resource.py | 11 - ...pt-html-via-cross-origin-blob-url.sub.html | 2 +- ...ith-json-parser-breaker.tentative.sub.html | 83 - .../fetch/data-urls/resources/data-urls.json | 2 +- .../fetch/http-cache/304-update.html | 30 - .../fetch/nosniff/parsing-nosniff.html | 28 + .../fetch/nosniff/parsing-nosniff.window.js | 24 - .../nosniff/resources/nosniff-first.asis | 7 + .../fetch/nosniff/resources/nosniff-last.asis | 7 + .../fetch/nosniff/resources/nosniff-no-x.asis | 6 + .../resources/nosniff-quoted-single.asis | 6 + .../nosniff/resources/nosniff-quoted.asis | 6 + .../nosniff/resources/nosniff-uppercase.asis | 6 + .../fetch/nosniff/resources/nosniff.py | 10 - .../resources/x-content-type-options.json | 58 - .../302-found-post-handler.py | 13 - .../redirect-navigate/302-found-post.html | 20 - .../fetch.tentative.https.sub.html | 6 +- .../report.tentative.https.sub.html | 44 +- .../fetch/sec-metadata/resources/helper.js | 1 + ...ocument-exit-fullscreen-timing-manual.html | 2 +- ...-ready-check-containing-iframe-manual.html | 29 +- ...lement-ready-check-not-allowed-manual.html | 22 +- ...est-fullscreen-and-exit-iframe-manual.html | 65 +- ...ment-request-fullscreen-timing-manual.html | 34 +- .../move-to-fullscreen-iframe-manual.html | 49 +- .../rendering/ua-style-iframe-manual.html | 19 +- .../generic-sensor/META.yml | 1 + .../generic-sensor-iframe-tests.sub.js | 28 +- .../wpt/web-platform-tests/gyroscope/META.yml | 1 + .../scroll-restoration-order.html | 74 - .../history/the-history-interface/001.html | 4 +- .../history/the-history-interface/002.html | 4 +- .../the-history-interface/blank-new.html | 5 - .../the-history-interface/blank-old.html | 5 - .../iframe_history_go_0.html | 40 - .../no-browsing-context.window.js | 86 - .../appcache/appcache-iframe.https.html | 37 - .../appcache/resources/appcache-data.py | 5 - .../resources/appcache-iframe.manifest | 8 - .../appcache/resources/appcache-iframe.py | 43 - .../workers/resources/appcache-worker.py | 1 - ..._when_term_nesting_level_nonzero.window.js | 113 - .../open-features-tokenization-noopener.html | 40 +- .../resources/message-opener.html | 4 +- .../window-properties.https.html | 13 - .../opener-setter.html | 1 - .../getter-tests.js | 27 - .../html/dom/interfaces.https.html | 3 +- .../html/editing/dnd/file/007.html | 2 +- .../html/editing/dnd/resources/32mb.py | 12 - .../flow-content-0/form-margin-quirk.html | 20 - ...sformed-tbody-tr-collapsed-border-ref.html | 18 - ...transformed-tbody-tr-collapsed-border.html | 23 - .../legend-block-margins-2-ref.html | 142 - .../legend-block-margins-2.html | 139 - .../legend-list-item-numbering-ref.html | 16 - .../legend-list-item-numbering.html | 17 - .../select-1-block-size-ref.html | 33 - .../select-1-block-size.html | 38 - .../select-1-line-height-ref.html | 23 - .../select-1-line-height.html | 35 - .../the-select-element/select-empty-ref.html | 35 - .../the-select-element/select-empty.html | 33 - .../the-link-element/link-style-error-01.html | 17 +- .../link-style-error-limited-quirks.html | 7 - .../link-style-error-quirks.html | 7 - .../the-link-element/resources/css.py | 7 - .../resources/link-style-error.js | 47 - .../attr-meta-http-equiv-refresh/parsing.html | 2 +- .../event_pause_noautoplay.html | 18 +- .../media-elements/event_play_noautoplay.html | 24 +- ...selection-invoke-set-src-networkState.html | 2 +- .../paused_true_during_pause.html | 6 +- .../play-in-detached-document.html | 3 +- .../track-element/track-change-event.html | 2 +- .../the-iframe-element/iframe-nosrc.html | 26 - .../the-img-element/available-images-ref.html | 2 - .../the-img-element/available-images.html | 17 - ...ecode-with-quick-attach-svg.tentative.html | 23 - ...ck-failed-cross-origin-navigation.sub.html | 52 - .../the-video-element/intrinsic_sizes.htm | 75 - .../form-target-iframe-helper.py | 3 - .../form-target-iframe.html | 29 - .../the-form-element/form-autocomplete.html | 63 +- .../the-input-element/type-change-state.html | 14 +- .../the-legend-element/HTMLLegendElement.html | 37 - .../execution-timing/077.html | 2 +- .../module/credentials.sub.html | 32 +- .../dynamic-imports-credentials.sub.html | 58 - .../resources/credentials-iframe.sub.html | 12 +- ...dynamic-import-credentials-iframe.sub.html | 26 - .../template-owner-document.html | 1 - ...torcookies-cookieenabled-false-manual.html | 17 - .../navigatorcookies-cookieenabled-true.html | 13 - .../assumptions/allowed-to-play.html | 23 - .../infrastructure/assumptions/blank.html | 2 - .../infrastructure/assumptions/cookie.html | 18 - .../assumptions/allowed-to-play.html.ini | 8 - .../assumptions/html-elements.html.ini | 9 - .../infrastructure/server/context.any.js.ini | 4 - .../server/order-of-metas.any.js.ini | 4 - .../server/secure-context.https.any.js.ini | 4 - .../infrastructure/server/title.any.js.ini | 4 - .../actions/elementPosition.html.ini | 3 - .../testdriver/actions/elementTiming.html.ini | 3 - .../testdriver/actions/eventOrder.html.ini | 3 - .../testdriver/actions/multiDevice.html.ini | 3 - .../testdriver/actions/elementPosition.html | 43 - .../testdriver/actions/elementTiming.html | 56 - .../testdriver/actions/eventOrder.html | 37 - .../testdriver/actions/multiDevice.html | 36 - .../infrastructure/testdriver/bless.html | 22 +- .../input-events-exec-command.html | 4 +- .../wpt/web-platform-tests/interfaces/CSP.idl | 23 +- .../interfaces/IndexedDB.idl | 7 - .../wpt/web-platform-tests/interfaces/SVG.idl | 2 +- .../interfaces/csp-embedded-enforcement.idl | 2 +- .../interfaces/css-layout-api.idl | 54 +- .../interfaces/cssom-view.idl | 2 - .../interfaces/fullscreen.idl | 2 +- .../web-platform-tests/interfaces/hr-time.idl | 3 +- .../web-platform-tests/interfaces/netinfo.idl | 10 +- .../interfaces/payment-request.idl | 18 +- .../interfaces/reporting.idl | 2 +- .../interfaces/screen-capture.idl | 14 +- .../interfaces/service-workers.idl | 8 - .../interfaces/speech-api.idl | 38 +- .../interfaces/touch-events.idl | 7 + .../interfaces/wasm-web-api.idl | 10 - .../interfaces/web-animations.idl | 2 +- .../interfaces/web-share.idl | 2 +- .../web-platform-tests/interfaces/webmidi.idl | 14 +- .../interfaces/webrtc-dscp.idl | 2 +- .../web-platform-tests/interfaces/webrtc.idl | 5 +- .../intersection-observer/bounding-box.html | 29 +- .../target-in-different-window.html | 36 - tests/wpt/web-platform-tests/lint.whitelist | 21 +- .../web-platform-tests/magnetometer/META.yml | 1 + .../scripts/underover-1.html | 2 +- .../media-capabilities/decodingInfo.html | 3 +- .../media-capabilities/encodingInfo.html | 328 - ...ediaRecorder-destroy-script-execution.html | 47 - .../MediaRecorder-error.html | 75 - .../MediaRecorder-stop.html | 50 - .../support/MediaRecorder-iframe.html | 28 - .../mediacapture-streams/META.yml | 1 - .../MediaDevices-SecureContext.html | 19 - ...iaStream-MediaElement-srcObject.https.html | 80 +- .../MediaStream-clone.https.html | 94 - ...iaStream-default-feature-policy.https.html | 2 +- .../MediaStream-idl.https.html | 41 +- .../MediaStreamTrack-getSettings.https.html | 170 +- .../idlharness.https.window.js | 6 +- .../mixed-content/generic/common.js | 3 - .../dom_interactive_image_document.html | 25 - .../dom_interactive_media_document.html | 25 - .../ondeviceorientationabsolute.html | 43 - .../orientation-sensor/META.yml | 1 + .../payment-handler/basic-card.js | 23 + .../can-make-payment-event.https.html | 7 + .../payment-instruments.https.html | 10 +- .../payment-request-event.https.html | 6 +- .../empty-data-manual.https.html | 16 +- .../historical.https.html | 25 - ...yment-request-ctor-pmi-handling.https.html | 149 - .../payment-request/META.yml | 4 +- .../PaymentItem/type_member.https.html | 77 + .../payment-request-abort-method.https.html | 66 +- ...anmakepayment-method-protection.https.html | 56 - ...t-request-canmakepayment-method.https.html | 209 +- .../payment-request-constructor.https.html | 3 + .../payment-request-id-attribute.https.html | 2 +- .../retry-method-manual.https.html | 28 +- .../rejects_if_not_active.https.html | 67 +- .../webtiming-resolution.any.js | 7 +- .../permissions/interfaces.any.js | 1 - .../test-background-fetch-permission.html | 15 - .../disable-picture-in-picture.html | 12 +- .../enter-picture-in-picture.html | 1 - .../exit-picture-in-picture.html | 1 - .../picture-in-picture/idlharness.window.js | 1 - .../leave-picture-in-picture.html | 1 - .../picture-in-picture-element.html | 1 - .../picture-in-picture-window.html | 4 - .../request-picture-in-picture-twice.html | 12 +- .../request-picture-in-picture.html | 11 +- .../resources/picture-in-picture-helpers.js | 15 +- .../picture-in-picture/shadow-dom.html | 11 +- .../web-platform-tests/pointerevents/META.yml | 1 + .../extension/pointerevent_constructor.html | 28 - ...ictedEvents_when_pointerlocked-manual.html | 76 - ...nt_predicted_events_attributes-manual.html | 149 - .../mouse_buttons_back_forward-manual.html | 9 +- .../PresentationRequest_error.https.html | 4 +- ...plePresentations_success-manual.https.html | 26 +- .../vertical-align-in-quirks-ref.html | 52 - .../quirks/vertical-align-in-quirks.html | 56 - .../referrer-policy/css-integration/README.md | 14 +- .../child-css/external-import-stylesheet.html | 48 - .../child-css/internal-import-stylesheet.html | 45 - .../child-css/processing-instruction.html | 47 - .../css-integration/css-test-helper.js | 66 - .../external-import-stylesheet.html | 50 + .../{image => }/external-stylesheet.html | 0 .../font-face/external-import-stylesheet.html | 53 - .../font-face/external-stylesheet.html | 47 - .../font-face/internal-import-stylesheet.html | 45 - .../font-face/internal-stylesheet.html | 45 - .../font-face/processing-instruction.html | 51 - .../image/external-import-stylesheet.html | 53 - .../{image => }/inline-style.html | 0 .../internal-import-stylesheet.html | 0 .../{image => }/internal-stylesheet.html | 0 .../{image => }/presentation-attribute.html | 0 .../{image => }/processing-instruction.html | 0 .../svg/external-stylesheet.html | 41 - .../css-integration/svg/inline-style.html | 35 - .../svg/internal-stylesheet.html | 35 - .../svg/presentation-attribute.html | 40 - .../svg/processing-instruction.html | 38 - .../generic/multiple-headers-and-values.html | 29 - .../multiple-headers-and-values.html.headers | 2 - .../generic/multiple-headers-combined.html | 29 - .../multiple-headers-combined.html.headers | 1 - .../generic/multiple-headers-one-invalid.html | 29 - .../multiple-headers-one-invalid.html.headers | 2 - .../multiple-headers-one-unknown-token.html | 29 - ...ple-headers-one-unknown-token.html.headers | 2 - .../generic/multiple-headers.html | 29 - .../generic/multiple-headers.html.headers | 2 - .../generic/subresource/font.py | 72 - .../generic/subresource/stylesheet.py | 56 +- .../generic/subresource/svg.py | 36 - .../generic/template/font.css.template | 9 - ...e.css.template => stylesheet.css.template} | 0 .../generic/template/svg.css.template | 3 - .../generic/template/svg.embedded.template | 5 - ...ource_TAO_cross_origin_redirect_chain.html | 9 +- ...esource_timing_buffer_full_eventually.html | 24 +- ...ce_timing_cross_origin_redirect_chain.html | 9 +- .../resource-timing/resources/TAOResponse.py | 10 +- .../resources/chromium/device.mojom.js | 340 +- .../chromium/generic_sensor_mocks.js | 2 +- .../resources/chromium/sensor.mojom.js | 44 +- .../resources/chromium/url.mojom.js | 79 - .../resources/chromium/webxr-test.js | 19 +- .../resources/idlharness.js | 394 +- .../resources/test/README.md | 2 +- .../resources/test/conftest.py | 19 +- .../test/tests/functional/api-tests-1.html | 8 +- .../test/tests/functional/log-insertion.html | 33 - .../IdlInterface/get_interface_object.html | 22 - .../get_interface_object_owner.html | 21 - .../IdlInterface/get_legacy_namespace.html | 20 - .../unit/IdlInterface/get_qualified_name.html | 20 - .../web-platform-tests/resources/test/tox.ini | 5 +- .../resources/test/wptserver.py | 6 +- .../resources/testdriver-actions.js | 391 - .../resources/testdriver.js | 33 - .../resources/testharness.js | 64 +- .../screen-capture/META.yml | 1 - .../screen-capture/getdisplaymedia.https.html | 199 +- .../screen-capture/idlharness.window.js | 4 +- .../selection/addRange.tentative.html | 29 - .../selection/stringifier.tentative.html | 28 - .../server-timing/cross_origin.html | 35 + .../server-timing/cross_origin.https.html | 35 - ...harness.https.any.js => idlharness.any.js} | 0 .../server-timing/navigation_timing_idl.html | 14 + .../navigation_timing_idl.https.html | 5 +- .../server-timing/resource_timing_idl.html | 14 + .../resource_timing_idl.https.html | 5 +- .../server_timing_header-parsing.html | 54 + .../server_timing_header-parsing.https.html | 4 +- .../service_worker_idl.https.html | 2 +- .../server-timing/test_server_timing.html | 45 + .../test_server_timing.html.sub.headers | 1 + .../test_server_timing.https.html | 4 +- .../activation-after-registration.https.html | 17 +- .../appcache-ordering-main.https.html | 12 +- .../claim-worker-fetch.https.html | 29 +- .../service-worker/client-id.https.html | 23 +- ...ients-matchall-exact-controller.https.html | 13 +- ...s-matchall-include-uncontrolled.https.html | 168 +- .../clients-matchall-order.https.html | 1 - .../clients-matchall.https.html | 23 +- .../controller-on-disconnect.https.html | 26 +- .../controller-on-load.https.html | 29 +- ...xtendable-event-async-waituntil.https.html | 40 +- .../extendable-event-waituntil.https.html | 115 +- .../fetch-audio-tainting.https.html | 47 - .../service-worker/fetch-cors-xhr.https.html | 22 +- .../fetch-event-referrer-policy.https.html | 12 +- .../fetch-frame-resource.https.html | 72 +- .../fetch-header-visibility.https.html | 12 +- .../fetch-request-css-base-url.https.html | 10 +- .../fetch-request-css-images.https.html | 162 +- .../fetch-request-html-imports.https.html | 13 +- ...ch-request-no-freshness-headers.https.html | 20 +- .../fetch-response-xhr.https.html | 21 +- .../fetch-waits-for-activate.https.html | 11 +- .../service-worker/getregistration.https.html | 28 +- .../import-module-scripts.https.html | 28 - .../import-scripts-mime-types.https.html | 30 - .../invalid-blobtype.https.html | 24 +- .../service-worker/invalid-header.https.html | 23 +- .../iso-latin1-header.https.html | 20 +- .../navigation-redirect.https.html | 452 +- ...sage-from-waiting-serviceworker.https.html | 9 +- ...message-to-client-message-queue.https.html | 211 - .../postmessage-to-client.https.html | 76 +- .../service-worker/referer.https.html | 22 +- .../registration-events.https.html | 35 +- .../about-blank-replacement-ping-frame.py | 1 - .../enable-client-message-queue.html | 39 - .../import-scripts-mime-types-worker.js | 49 - .../resources/imported-classic-script.js | 1 - .../resources/imported-module-script.js | 1 - .../resources/message-vs-microtask.html | 18 - .../navigation-redirect-other-origin.html | 19 - .../navigation-redirect-out-scope.py | 4 +- .../resources/navigation-redirect-scope1.py | 4 +- .../resources/navigation-redirect-scope2.py | 4 +- .../resources/nested-iframe-parent.html | 5 - .../resources/redirect-worker.js | 55 +- .../registration-tests-mime-types.js | 14 +- .../resources/service-worker-header.py | 21 +- .../resources/stalling-service-worker.js | 54 - .../update-during-installation-worker.js | 23 - ...-missing-import-scripts-imported-worker.py | 9 - ...date-missing-import-scripts-main-worker.py | 13 - .../update-registration-with-type.py | 33 - .../service-worker-header.https.html | 21 +- .../service-worker/state.https.html | 29 +- .../uncontrolled-page.https.html | 14 +- .../unregister-then-register.https.html | 60 +- .../update-missing-import-scripts.https.html | 33 - .../update-not-allowed.https.html | 58 - .../service-worker/update-recovery.https.html | 12 +- .../update-registration-with-type.https.html | 74 - .../service-worker/websocket.https.html | 31 +- .../shadow-dom/slots-outside-shadow-dom.html | 16 - .../signed-exchange/META.yml | 5 - .../signed-exchange/README.md | 22 - .../fallback-to-another-sxg.tentative.html | 17 - .../signed-exchange/nested-sxg.tentative.html | 17 - .../resources/127.0.0.1.sxg.ext | 7 - .../resources/127.0.0.1.sxg.key | 8 - .../resources/127.0.0.1.sxg.pem | 11 - .../resources/127.0.0.1.sxg.pem.cbor | Bin 440 -> 0 bytes .../resources/127.0.0.1.sxg.pem.cbor.headers | 1 - .../signed-exchange/resources/failure.html | 7 - .../resources/fallback-to-another-sxg.sxg | Bin 952 -> 0 bytes .../fallback-to-another-sxg.sxg.headers | 1 - .../resources/generate-test-certs.sh | 19 - .../resources/generate-test-sxgs.sh | 87 - .../signed-exchange/resources/inner-url.html | 7 - .../signed-exchange/resources/nested-sxg.sxg | Bin 1945 -> 0 bytes .../resources/nested-sxg.sxg.headers | 1 - .../resources/sxg-invalid-validity-url.sxg | Bin 937 -> 0 bytes .../sxg-invalid-validity-url.sxg.headers | 1 - .../resources/sxg-location.html | 7 - .../resources/sxg-location.sxg | Bin 957 -> 0 bytes .../resources/sxg-location.sxg.headers | 1 - .../signed-exchange/resources/sxg-util.js | 40 - .../sxg-double-prefetch.tentative.html | 37 - .../sxg-fallback-with-fragment.tentative.html | 17 - .../sxg-invalid-validity-url.tentative.html | 19 - .../sxg-location-fragment.tentative.html | 17 - .../sxg-location.tentative.html | 17 - .../sxg-non-secure-origin.tentative.html | 20 - ...xg-prefetch-resource-timing.tentative.html | 44 - .../web-platform-tests/speech-api/META.yml | 2 +- ...ak-without-activation-fails.tentative.html | 2 +- ...SpeechSynthesisErrorEvent-constructor.html | 88 - .../SpeechSynthesisEvent-constructor.html | 67 - ...SpeechSynthesisUtterance-basics.https.html | 11 - .../speech-api/idlharness.window.js | 32 +- .../streams/piping/abort.dedicatedworker.html | 11 - .../streams/piping/abort.html | 11 - .../streams/piping/abort.js | 365 - .../piping/abort.serviceworker.https.html | 12 - .../streams/piping/abort.sharedworker.html | 11 - .../subresource-integrity/META.yml | 2 + .../svg/import/animate-elem-83-t-manual.svg | 2 +- .../svg/interact/inheritance.svg | 22 - .../parsing/pointer-events-invalid.svg | 21 - .../interact/parsing/pointer-events-valid.svg | 29 - .../reftests/use-hidden-attr-change.html | 32 - .../filter-effects-on-pattern-ref.html | 3 - .../reftests/filter-effects-on-pattern.html | 14 - .../svg/shapes/circle-01-ref.svg | 3 - .../svg/shapes/circle-01.svg | 9 - .../svg/shapes/ellipse-09.svg | 11 - .../svg/shapes/rect-05-ref.svg | 3 - .../web-platform-tests/svg/shapes/rect-05.svg | 11 - .../SVGGeometryElement.isPointInFill-01.svg | 113 - .../SVGGeometryElement.isPointInStroke-01.svg | 160 - tests/wpt/web-platform-tests/tools/META.yml | 1 - .../wpt/web-platform-tests/tools/appveyor.yml | 32 + .../tools/ci/before_install.sh | 6 +- .../tools/ci/check_stability.py | 6 +- .../tools/ci/ci_built_diff.sh | 4 +- .../web-platform-tests/tools/ci/ci_lint.sh | 6 +- .../tools/ci/ci_manifest.sh | 4 +- .../tools/ci/ci_resources_unittest.sh | 4 +- .../tools/ci/ci_stability.sh | 4 +- .../tools/ci/ci_tools_unittest.sh | 13 +- .../wpt/web-platform-tests/tools/ci/ci_wpt.sh | 4 +- .../tools/ci/ci_wptrunner_infrastructure.sh | 10 +- .../web-platform-tests/tools/ci/install.sh | 4 +- tests/wpt/web-platform-tests/tools/ci/jobs.py | 4 - tests/wpt/web-platform-tests/tools/ci/run.sh | 4 +- .../web-platform-tests/tools/ci/tag_master.py | 2 +- .../tools/ci/taskcluster-run.py | 10 +- .../web-platform-tests/tools/ci/tcdownload.py | 6 +- .../tools/ci/tests/test_jobs.py | 26 +- .../tools/docker/Dockerfile | 2 +- tests/wpt/web-platform-tests/tools/flake8.ini | 21 + .../wpt/web-platform-tests/tools/lint/lint.py | 7 +- .../about_blank-ref.html} | 0 .../tools/lint/tests/test_lint.py | 7 +- .../tools/manifest/sourcefile.py | 1 - .../tools/manifest/tests/test_sourcefile.py | 2 - .../web-platform-tests/tools/manifest/vcs.py | 10 +- .../web-platform-tests/tools/py27-flake8.ini | 28 - .../web-platform-tests/tools/py36-flake8.ini | 26 - .../tools/requirements_flake8.txt | 4 - .../tools/runner/index.html | 14 +- .../web-platform-tests/tools/runner/logo.svg | 8 + .../tools/serve/test_functional.py | 2 +- tests/wpt/web-platform-tests/tools/tox.ini | 20 +- .../tools/webdriver/webdriver/client.py | 7 + .../web-platform-tests/tools/wpt/browser.py | 130 +- .../web-platform-tests/tools/wpt/install.py | 8 +- .../web-platform-tests/tools/wpt/markdown.py | 2 - .../tools/wpt/requirements.txt | 2 +- tests/wpt/web-platform-tests/tools/wpt/run.py | 51 +- .../web-platform-tests/tools/wpt/testfiles.py | 19 +- .../tools/wpt/tests/test_browser.py | 32 - .../tools/wpt/tests/test_run.py | 47 - .../tools/wpt/tests/test_wpt.py | 52 +- .../wpt/web-platform-tests/tools/wpt/tox.ini | 13 +- .../wpt/web-platform-tests/tools/wpt/utils.py | 32 +- .../tools/wpt/virtualenv.py | 2 +- .../tools/wptrunner/docs/design.rst | 2 +- .../tools/wptrunner/requirements.txt | 6 +- .../tools/wptrunner/requirements_chrome.txt | 2 +- .../wptrunner/requirements_chrome_android.txt | 2 +- .../tools/wptrunner/requirements_edge.txt | 2 +- .../tools/wptrunner/requirements_firefox.txt | 8 +- .../tools/wptrunner/requirements_ie.txt | 2 +- .../tools/wptrunner/requirements_opera.txt | 2 +- .../tools/wptrunner/requirements_safari.txt | 2 +- .../tools/wptrunner/requirements_sauce.txt | 4 +- .../tools/wptrunner/tox.ini | 13 +- .../wptrunner/wptrunner/browsers/__init__.py | 3 +- .../wptrunner/wptrunner/browsers/chrome.py | 42 +- .../wptrunner/browsers/chrome_webdriver.py | 50 + .../wptrunner/wptrunner/browsers/fennec.py | 25 +- .../wptrunner/wptrunner/browsers/firefox.py | 34 +- .../wptrunner/browsers/servodriver.py | 2 +- .../wptrunner/wptrunner/browsers/webkit.py | 44 +- .../wptrunner/wptrunner/executors/base.py | 74 +- .../wptrunner/executors/executormarionette.py | 45 +- .../wptrunner/executors/executorselenium.py | 48 +- .../wptrunner/executors/executorservo.py | 2 +- .../wptrunner/executors/executorwebdriver.py | 46 +- .../wptrunner/wptrunner/executors/protocol.py | 22 - .../wptrunner/wptrunner/executors/runner.js | 59 - .../executors/testharness_webdriver.js | 26 +- .../executors/testharness_webdriver_resume.js | 63 +- .../tools/wptrunner/wptrunner/formatters.py | 53 +- .../wptrunner/wptrunner/manifestexpected.py | 11 - .../tools/wptrunner/wptrunner/stability.py | 7 +- .../wptrunner/wptrunner/testdriver-extra.js | 18 - .../tools/wptrunner/wptrunner/testrunner.py | 115 +- .../tools/wptrunner/wptrunner/tests/base.py | 2 +- .../wptrunner/tests/test_formatters.py | 73 - .../wptrunner/tests/test_stability.py | 3 - .../wptrunner/wptrunner/tests/test_wpttest.py | 46 - .../wptrunner/wptrunner/wptcommandline.py | 14 +- .../tools/wptrunner/wptrunner/wptrunner.py | 15 +- .../tools/wptrunner/wptrunner/wpttest.py | 13 - .../tools/wptserve/.travis.yml | 24 + .../tools/wptserve/tests/functional/base.py | 9 +- .../tests/functional/test_handlers.py | 21 +- .../wptserve/tests/functional/test_pipes.py | 54 +- .../wptserve/tests/functional/test_request.py | 67 +- .../tests/functional/test_response.py | 14 +- .../tools/wptserve/wptserve/constants.py | 51 +- .../tools/wptserve/wptserve/handlers.py | 4 +- .../tools/wptserve/wptserve/pipes.py | 26 +- .../tools/wptserve/wptserve/ranges.py | 4 - .../tools/wptserve/wptserve/request.py | 58 +- .../tools/wptserve/wptserve/response.py | 4 +- .../tools/wptserve/wptserve/server.py | 2 +- .../Document-write.tentative.html | 5 +- .../Element-insertAdjacentHTML.tentative.html | 14 +- ...createPolicy-createXYZTests.tentative.html | 24 +- ...olicy-cspTests-noNamesGiven.tentative.html | 7 +- ...atePolicy-cspTests-wildcard.tentative.html | 14 - ...y-createPolicy-defaultTests.tentative.html | 13 - ...stedTypePolicyFactory-isXXX.tentative.html | 118 - .../Window-TrustedTypes.tentative.html | 6 - ...o-DOMParser-parseFromString.tentative.html | 17 +- ...mers-setTimeout-setInterval.tentative.html | 15 +- ...ssignment-to-Document-write.tentative.html | 4 +- ...-Element-insertAdjacentHTML.tentative.html | 68 +- ...gnment-to-Element-outerHTML.tentative.html | 26 +- ...ent-to-Element-setAttribute.tentative.html | 51 +- ...t-to-Element-setAttributeNS.tentative.html | 2 +- ...ment-to-HTMLElement-generic.tentative.html | 37 +- ...signment-to-Location-assign.tentative.html | 18 +- ...assignment-to-Location-href.tentative.html | 19 +- ...ignment-to-Location-replace.tentative.html | 18 +- ...ge-createContextualFragment.tentative.html | 19 +- ...g-assignment-to-Window-open.tentative.html | 28 +- .../trusted-types/support/helper.sub.js | 12 +- .../mouse_buttons_back_forward-manual.html | 6 +- tests/wpt/web-platform-tests/url/META.yml | 1 + .../url/resources/urltestdata.json | 16 - .../web-platform-tests/wasm/idlharness.any.js | 33 + .../wasm/jsapi/assertions.js | 21 - .../wasm/jsapi/constructor/compile.any.js | 11 +- .../wasm/jsapi/constructor/instantiate.any.js | 28 +- .../wasm/jsapi/constructor/validate.any.js | 4 - .../wasm/jsapi/global/constructor.any.js | 6 - .../wasm/jsapi/global/value-get-set.any.js | 111 - .../wasm/jsapi/global/value-set.any.js | 94 + .../wasm/jsapi/global/valueOf.any.js | 6 - .../wasm/jsapi/idlharness.any.js | 40 - .../wasm/jsapi/instance/exports.any.js | 14 - .../wasm/jsapi/instanceTestFactory.js | 23 +- .../wasm/jsapi/memory/buffer.any.js | 14 - .../wasm/jsapi/memory/constructor.any.js | 6 - .../wasm/jsapi/memory/grow.any.js | 15 - .../wasm/jsapi/module/constructor.any.js | 10 - .../wasm/jsapi/module/customSections.any.js | 5 - .../wasm/jsapi/module/exports.any.js | 16 +- .../wasm/jsapi/module/imports.any.js | 6 - .../wasm/jsapi/table/constructor.any.js | 6 - .../wasm/jsapi/table/get-set.any.js | 16 +- .../wasm/jsapi/table/grow.any.js | 10 - .../wasm/jsapi/table/length.any.js | 14 - .../wasm/jsapi/wasm-constants.js | 67 +- .../wasm/jsapi/wasm-module-builder.js | 237 +- .../wasm/resources/load_wasm.js | 2 +- .../wasm/webapi/abort.any.js | 24 - .../wasm/webapi/body.any.js | 20 - .../wasm/webapi/contenttype.any.js | 45 - .../wasm/webapi/empty-body.any.js | 20 - .../wasm/webapi/idlharness.any.js | 10 - .../instantiateStreaming-bad-imports.any.js | 14 - .../wasm/webapi/instantiateStreaming.any.js | 20 - .../wasm/webapi/invalid-args.any.js | 28 - .../wasm/webapi/invalid-code.any.js | 16 - .../wasm/webapi/origin.sub.any.js | 15 - .../wasm/webapi/rejected-arg.any.js | 9 - .../wasm/webapi/status.any.js | 21 - .../web-platform-tests/wasm/webapi/status.py | 4 - .../animation-types/property-list.js | 2 +- .../animation-types/property-types.js | 14 +- .../timing-model/animations/play-states.html | 40 +- .../transformed-progress.html | 107 +- .../web-locks/web-locks.idl | 2 +- tests/wpt/web-platform-tests/web-nfc/META.yml | 1 + .../wpt/web-platform-tests/webaudio/META.yml | 1 + .../webaudio/js/worklet-recorder.js | 54 - .../webaudio/resources/4ch-440.wav | Bin 353022 -> 0 bytes .../audiobuffer-reuse.html | 36 - ...iobuffersource-multi-channels-expected.wav | Bin .../audiobuffersource-multi-channels.html | 22 +- .../event-insertion.html | 7 - ...t-postmessage-sharedarraybuffer.https.html | 85 - .../processors/sharedarraybuffer-processor.js | 35 - ...convolver-setBuffer-already-has-value.html | 6 +- .../the-gainnode-interface/gain-expected.wav | Bin 0 -> 281400 bytes .../cors-check.https.html | 74 - .../no-cors.https.html | 73 - .../{get_page_source => actions}/__init__.py | 0 .../webdriver/tests/actions/conftest.py | 40 + .../webdriver/tests/actions/control_click.py | 77 + .../webdriver/tests/actions/key.py | 193 + .../webdriver/tests/actions/key_shortcuts.py | 49 + .../webdriver/tests/actions/modifier_click.py | 84 + .../webdriver/tests/actions/mouse.py | 144 + .../webdriver/tests/actions/mouse_dblclick.py | 32 + .../tests/actions/mouse_pause_dblclick.py | 52 + .../{perform_actions => actions}/none.py | 0 .../webdriver/tests/actions/pointer_origin.py | 129 + .../webdriver/tests/actions/sequence.py | 88 + .../webdriver/tests/actions/special_keys.py | 82 + .../support}/__init__.py | 0 .../support/keys.py | 0 .../support/mouse.py | 0 .../support/refine.py | 0 .../support/test_actions_wdspec.html | 0 .../{perform_actions => actions}/validity.py | 0 .../tests/add_cookie/user_prompts.py | 137 - .../webdriver/tests/conftest.py | 234 +- .../tests/delete_all_cookies/user_prompts.py | 119 - .../webdriver/tests/element_clear/clear.py | 3 +- .../tests/element_clear/user_prompts.py | 132 - .../tests/element_click/center_point.py | 87 - .../tests/element_click/interactability.py | 91 +- .../tests/element_click/user_prompts.py | 123 - .../tests/element_send_keys/file_upload.py | 86 - .../element_send_keys/interactability.py | 26 +- .../webdriver/tests/execute_script/promise.py | 114 - .../tests/find_element/user_prompts.py | 121 - .../find_element_from_element/user_prompts.py | 126 - .../tests/find_elements/user_prompts.py | 123 - .../user_prompts.py | 128 - .../tests/fullscreen_window/fullscreen.py | 20 +- .../tests/fullscreen_window/user_prompts.py | 26 +- .../webdriver/tests/get_active_element/get.py | 57 +- .../tests/get_active_element/user_prompts.py | 119 - .../webdriver/tests/get_current_url/get.py | 7 +- .../get_element_attribute/user_prompts.py | 118 - .../tests/get_element_rect/__init__.py | 11 +- .../webdriver/tests/get_element_rect/get.py | 5 +- .../tests/get_element_rect/user_prompts.py | 5 +- .../tests/get_element_text/user_prompts.py | 117 - .../tests/get_named_cookie/user_prompts.py | 118 - .../tests/get_page_source/user_prompts.py | 113 - .../webdriver/tests/get_title/get.py | 10 +- .../tests/maximize_window/maximize.py | 18 +- .../tests/minimize_window/minimize.py | 34 +- .../tests/minimize_window/user_prompts.py | 22 +- .../tests/navigate_to/user_prompts.py | 113 - .../webdriver/tests/new_session/response.py | 2 - .../tests/new_session/support/create.py | 32 +- .../support => page_source}/__init__.py | 0 .../source.py | 0 .../tests/perform_actions/conftest.py | 40 - .../webdriver/tests/perform_actions/key.py | 33 - .../tests/perform_actions/key_events.py | 205 - .../tests/perform_actions/key_modifiers.py | 37 - .../tests/perform_actions/key_shortcuts.py | 49 - .../tests/perform_actions/key_special_keys.py | 38 - .../tests/perform_actions/pointer.py | 141 - .../perform_actions/pointer_contextmenu.py | 77 - .../tests/perform_actions/pointer_dblclick.py | 32 - .../perform_actions/pointer_modifier_click.py | 84 - .../tests/perform_actions/pointer_origin.py | 129 - .../perform_actions/pointer_pause_dblclick.py | 52 - .../tests/perform_actions/sequence.py | 9 - .../tests/perform_actions/user_prompts.py | 124 - .../tests/release_actions/__init__.py | 0 .../tests/release_actions/conftest.py | 40 - .../tests/release_actions/release.py | 18 - .../tests/release_actions/sequence.py | 82 - .../tests/release_actions/support/__init__.py | 0 .../tests/release_actions/support/refine.py | 33 - .../support/test_actions_wdspec.html | 197 - .../webdriver/tests/set_window_rect/set.py | 20 +- .../webdriver/tests/support/asserts.py | 21 - .../webdriver/tests/support/fixtures.py | 233 - .../webdriver/tests/support/helpers.py | 41 - .../webdriver/tests/support/image.py | 12 - .../webdriver/tests/support/inline.py | 2 +- .../webdriver/tests/support/sync.py | 146 - .../webdriver/tests/support/wait.py | 38 + .../tests/take_element_screenshot/__init__.py | 12 - .../take_element_screenshot/screenshot.py | 29 +- .../take_element_screenshot/user_prompts.py | 8 +- .../tests/take_screenshot/__init__.py | 6 - .../tests/take_screenshot/screenshot.py | 14 +- .../tests/take_screenshot/user_prompts.py | 8 +- ...igin.html => broken-origin.tentative.html} | 0 ...ml => host-specific-origin.tentative.html} | 0 ...ssage-channel-transferable.tentative.html} | 0 ...n.html => no-target-origin.tentative.html} | 0 ...sfer.html => null-transfer.tentative.html} | 0 .../{one-arg.html => one-arg.tentative.html} | 0 ...rigin.html => slash-origin.tentative.html} | 0 ... => undefined-transferable.tentative.html} | 0 ....html => unknown-parameter.tentative.html} | 0 .../webmessaging/without-ports/008.html | 9 +- ...s.https.window.js => idlharness.window.js} | 0 .../webrtc-identity/META.yml | 4 - .../RTCPeerConnection-constructor.html | 11 - .../web-platform-tests/webrtc-stats/META.yml | 1 - tests/wpt/web-platform-tests/webrtc/META.yml | 1 - .../webrtc/RTCCertificate-postMessage.html | 77 - .../webrtc/RTCCertificate.html | 13 +- .../webrtc/RTCDTMFSender-helper.js | 8 +- .../RTCDTMFSender-ontonechange.https.html | 20 +- .../webrtc/RTCIceCandidate-constructor.html | 24 +- .../RTCIceTransport-extension-helper.js | 42 - .../RTCIceTransport-extension.https.html | 73 +- .../webrtc/RTCIceTransport.html | 2 +- .../RTCPeerConnection-addIceCandidate.html | 154 +- .../RTCPeerConnection-addTrack.https.html | 13 + ...TCPeerConnection-addTransceiver.https.html | 50 + .../RTCPeerConnection-connectionState.html | 4 +- .../webrtc/RTCPeerConnection-constructor.html | 3 + .../RTCPeerConnection-createAnswer.html | 7 +- ...Connection-createOffer-offerToReceive.html | 185 + .../webrtc/RTCPeerConnection-createOffer.html | 93 +- ...erConnection-getIdentityAssertion.sub.html | 0 .../webrtc/RTCPeerConnection-helper.js | 125 +- .../RTCPeerConnection-peerIdentity.html | 0 ...eerConnection-remote-track-mute.https.html | 98 - ...Connection-setLocalDescription-answer.html | 7 +- ...rConnection-setLocalDescription-offer.html | 16 +- ...nnection-setLocalDescription-pranswer.html | 8 +- ...RTCPeerConnection-setLocalDescription.html | 10 +- ...onnection-setRemoteDescription-answer.html | 3 +- ...nection-setRemoteDescription-pranswer.html | 7 +- ...tRemoteDescription-replaceTrack.https.html | 62 +- ...nection-setRemoteDescription-rollback.html | 4 +- ...ion-setRemoteDescription-tracks.https.html | 9 +- ...TCPeerConnection-setRemoteDescription.html | 8 +- .../RTCPeerConnection-transceivers.https.html | 75 +- ...RTCPeerConnectionIceEvent-constructor.html | 30 +- .../webrtc/RTCQuicStream.https.html | 133 +- .../webrtc/RTCQuicTransport-helper.js | 77 +- .../webrtc/RTCQuicTransport.https.html | 158 +- .../webrtc/RTCRtpParameters-encodings.html | 46 +- .../webrtc/RTCRtpParameters-helper.js | 36 + .../webrtc/RTCRtpReceiver-getParameters.html | 7 +- .../webrtc/RTCRtpReceiver-getStats.https.html | 6 - .../webrtc/RTCRtpSender-getStats.https.html | 6 +- .../webrtc/RTCRtpTransceiver-direction.html | 94 - .../RTCRtpTransceiver-setDirection.html | 95 + .../webrtc/RTCRtpTransceiver.https.html | 313 +- .../webrtc/RTCSctpTransport-constructor.html | 4 +- .../RTCSctpTransport-maxMessageSize.html | 10 +- .../web-platform-tests/webrtc/getstats.html | 7 +- .../web-platform-tests/webrtc/historical.html | 8 - .../identity-helper.sub.js | 0 .../webrtc/idlharness.https.window.js | 4 +- .../webrtc/legacy/README.txt | 2 - ...Connection-createOffer-offerToReceive.html | 274 - ...ver-with-OfferToReceive-options.https.html | 169 - .../webrtc/legacy/onaddstream.https.html | 153 - .../webrtc/no-media-call.html | 5 +- .../protocol/jsep-initial-offer.https.html | 35 - .../webrtc/protocol/video-codecs.https.html | 2 +- .../RTCCertificate-postMessage-iframe.html | 9 - .../webrtc/simplecall-no-ssrcs.https.html | 122 - .../webrtc/tools/.eslintrc.js | 2 +- .../websockets/Close-1000-reason.any.js | 4 +- .../websockets/Close-1000.any.js | 4 +- .../websockets/Close-Reason-124Bytes.any.js | 2 +- .../Close-reason-unpaired-surrogates.any.js | 4 +- .../Create-Secure-extensions-empty.any.js | 4 +- .../Create-Secure-url-with-space.any.js | 2 +- ...te-Secure-valid-url-array-protocols.any.js | 4 +- ...te-Secure-valid-url-binaryType-blob.any.js | 4 +- ...ure-valid-url-protocol-setCorrectly.any.js | 4 +- ...te-Secure-valid-url-protocol-string.any.js | 4 +- .../websockets/Create-Secure-valid-url.any.js | 4 +- ...ure-verify-url-set-non-default-port.any.js | 2 +- .../Create-asciiSep-protocol-string.any.js | 2 +- .../websockets/Create-non-absolute-url.any.js | 2 +- .../Create-nonAscii-protocol-string.any.js | 2 +- .../Create-protocol-with-space.any.js | 2 +- ...protocols-repeated-case-insensitive.any.js | 2 +- .../Create-protocols-repeated.any.js | 2 +- .../Create-valid-url-array-protocols.any.js | 4 +- .../Create-valid-url-protocol-empty.any.js | 2 +- .../Create-valid-url-protocol.any.js | 4 +- .../websockets/Create-valid-url.any.js | 4 +- ...ate-verify-url-set-non-default-port.any.js | 2 +- .../websockets/Create-wrong-scheme.any.js | 2 +- .../Secure-Close-1000-reason.any.js | 4 +- .../Secure-Close-1000-verify-code.any.js | 4 +- .../websockets/Secure-Close-1000.any.js | 4 +- .../Secure-Close-1005-verify-code.any.js | 4 +- .../websockets/Secure-Close-1005.any.js | 2 +- .../Secure-Close-2999-reason.any.js | 2 +- .../Secure-Close-3000-reason.any.js | 4 +- .../Secure-Close-3000-verify-code.any.js | 4 +- .../Secure-Close-4999-reason.any.js | 4 +- .../Secure-Close-Reason-124Bytes.any.js | 2 +- ...re-Close-Reason-Unpaired-surrogates.any.js | 4 +- .../websockets/Secure-Close-onlyReason.any.js | 2 +- .../Secure-Close-readyState-Closed.any.js | 4 +- .../Secure-Close-readyState-Closing.any.js | 2 +- ...Secure-Close-server-initiated-close.any.js | 4 +- .../websockets/Secure-Send-65K-data.any.js | 6 +- .../Secure-Send-binary-65K-arraybuffer.any.js | 6 +- .../Secure-Send-binary-arraybuffer.any.js | 6 +- ...Send-binary-arraybufferview-float32.any.js | 6 +- ...Send-binary-arraybufferview-float64.any.js | 6 +- ...e-Send-binary-arraybufferview-int32.any.js | 6 +- ...rraybufferview-uint16-offset-length.any.js | 6 +- ...inary-arraybufferview-uint32-offset.any.js | 6 +- ...arraybufferview-uint8-offset-length.any.js | 6 +- ...binary-arraybufferview-uint8-offset.any.js | 6 +- .../websockets/Secure-Send-binary-blob.any.js | 6 +- .../websockets/Secure-Send-data.any.js | 6 +- .../websockets/Secure-Send-null.any.js | 6 +- .../Secure-Send-paired-surrogates.any.js | 6 +- .../Secure-Send-unicode-data.any.js | 6 +- .../Secure-Send-unpaired-surrogates.any.js | 6 +- .../websockets/Send-0byte-data.any.js | 6 +- .../websockets/Send-65K-data.any.js | 6 +- .../Send-Unpaired-Surrogates.any.js | 6 +- .../websockets/Send-before-open.any.js | 2 +- .../Send-binary-65K-arraybuffer.any.js | 6 +- .../websockets/Send-binary-arraybuffer.any.js | 6 +- ...binary-arraybufferview-int16-offset.any.js | 6 +- .../Send-binary-arraybufferview-int8.any.js | 6 +- .../websockets/Send-binary-blob.any.js | 6 +- .../websockets/Send-data.any.js | 6 +- .../websockets/Send-data.worker.js | 2 +- .../websockets/Send-null.any.js | 6 +- .../websockets/Send-paired-surrogates.any.js | 6 +- .../websockets/Send-unicode-data.any.js | 6 +- .../websockets/binaryType-wrong-value.any.js | 4 +- .../003-sets-origin.worker.js | 2 +- .../webstorage/event_constructor.html | 87 +- .../event_constructor_eventinit.html | 34 + .../webstorage/event_initstorageevent.html | 72 - .../event_local_storageeventinit.html | 37 + .../event_session_storageeventinit.html | 36 + .../webstorage/missing_arguments.html | 3 + .../webusb/resources/usb-helpers.js | 1 - .../processing-model/align_center-ref.html | 26 - .../processing-model/align_center.html | 22 - .../align_center_position_50-ref.html | 26 - .../align_center_position_50.html | 22 - .../align_center_position_gt_50-ref.html | 26 - .../align_center_position_gt_50.html | 22 - .../align_center_position_lt_50-ref.html | 27 - .../align_center_position_lt_50.html | 22 - ...sition_lt_50_size_gt_maximum_size-ref.html | 27 - ...r_position_lt_50_size_gt_maximum_size.html | 22 - .../align_center_wrapped-ref.html | 26 - .../align_center_wrapped.html | 22 - .../processing-model/align_middle-ref.html | 26 + .../processing-model/align_middle.html | 22 + .../align_middle_position_50-ref.html | 26 + .../align_middle_position_50.html | 22 + .../align_middle_position_gt_50-ref.html | 26 + .../align_middle_position_gt_50.html | 22 + .../align_middle_position_lt_50-ref.html | 27 + .../align_middle_position_lt_50.html | 22 + ...sition_lt_50_size_gt_maximum_size-ref.html | 27 + ...e_position_lt_50_size_gt_maximum_size.html | 22 + .../align_middle_wrapped-ref.html | 26 + .../align_middle_wrapped.html | 22 + .../processing-model/regions/basic-ref.html | 26 - .../processing-model/regions/basic.html | 22 - .../regionanchor_x_50_percent-ref.html | 26 - .../regions/regionanchor_x_50_percent.html | 22 - .../regionanchor_y_50_percent-ref.html | 6 - .../regions/regionanchor_y_50_percent.html | 22 - .../regions/scroll_up-ref.html | 26 - .../processing-model/regions/scroll_up.html | 22 - .../regions/single_line_top_left-ref.html | 26 - .../regions/single_line_top_left.html | 22 - .../regions/support/basic.vtt | 7 - .../support/regionanchor_x_50_percent.vtt | 8 - .../support/regionanchor_y_50_percent.vtt | 8 - .../regions/support/scroll_up.vtt | 16 - .../regions/support/single_line_top_left.vtt | 10 - .../support/viewportanchor_x_50_percent.vtt | 8 - .../support/viewportanchor_y_50_percent.vtt | 8 - .../regions/support/width_50_percent.vtt | 8 - .../viewportanchor_x_50_percent-ref.html | 27 - .../regions/viewportanchor_x_50_percent.html | 22 - .../viewportanchor_y_50_percent-ref.html | 26 - .../regions/viewportanchor_y_50_percent.html | 22 - .../regions/width_50_percent-ref.html | 26 - .../regions/width_50_percent.html | 22 - .../processing-model/support/align_center.vtt | 4 - .../support/align_center_long.vtt | 4 - .../support/align_center_position_50.vtt | 4 - .../support/align_center_position_gt_50.vtt | 4 - .../support/align_center_position_lt_50.vtt | 4 - ...er_position_lt_50_size_gt_maximum_size.vtt | 4 - .../processing-model/support/align_middle.vtt | 4 + .../support/align_middle_long.vtt | 4 + .../support/align_middle_position_50.vtt | 4 + .../support/align_middle_position_gt_50.vtt | 4 + .../support/align_middle_position_lt_50.vtt | 4 + ...le_position_lt_50_size_gt_maximum_size.vtt | 4 + .../webxr/resources/webxr_util.js | 1 + .../Worker_cross_origin_security_err.htm | 19 +- .../SharedWorker/same-origin.html | 5 +- .../constructors/Worker/same-origin.html | 23 +- .../dedicated-worker-import-blob-url.any.js | 2 +- .../dedicated-worker-import-data-url.any.js | 1 - .../dedicated-worker-import-failure.html | 1 - .../modules/dedicated-worker-import.any.js | 1 - .../dedicated-worker-options-credentials.html | 268 +- ...ed-worker-options-credentials.html.headers | 2 +- .../workers/modules/resources/credentials.py | 1 - ...ic-import-and-then-static-import-worker.js | 22 +- ...e-origin-credentials-checker-worker.sub.js | 2 - ...-same-origin-credentials-checker-worker.js | 1 - .../resources/dynamic-import-worker.js | 22 +- .../resources/eval-dynamic-import-worker.js | 19 +- .../export-on-dynamic-import-script.js | 3 +- .../modules/resources/import-test-cases.js | 14 +- .../resources/nested-dynamic-import-worker.js | 27 +- .../resources/nested-static-import-worker.js | 9 +- .../modules/resources/new-worker-window.html | 5 +- ...c-import-and-then-dynamic-import-worker.js | 22 +- ...e-origin-credentials-checker-worker.sub.js | 2 - ...-same-origin-credentials-checker-worker.js | 1 - .../modules/resources/static-import-worker.js | 9 +- .../semantics/interface-objects/001.worker.js | 2 - .../semantics/interface-objects/002.worker.js | 2 + .../semantics/interface-objects/003.html | 2 - .../semantics/interface-objects/004.html | 2 + .../xhr/getallresponseheaders.htm | 42 +- .../xhr/getresponseheader.any.js | 37 +- .../xhr/overridemimetype-edge-cases.window.js | 14 +- ...imetype-unsent-state-force-shiftjis.any.js | 12 - ...demimetype-unsent-state-force-shiftjis.htm | 27 + .../header-content-length-twice.asis | 3 - .../xhr/resources/headers-double-empty.asis | 3 - .../xhr/resources/headers-some-are-empty.asis | 7 - .../xhr/resources/inspect-headers.py | 8 +- .../responseXML-unavailable-in-worker.js | 4 +- .../xhr/send-content-type-charset.htm | 26 +- .../xhr/setrequestheader-combining.window.js | 12 - .../xhr/setrequestheader-header-allowed.htm | 1 - tests/wpt/webgl/meta/MANIFEST.json | 6 +- .../extensions/oes-texture-float.html.ini | 4 + .../oes-texture-half-float.html.ini | 56 +- .../glsl/variables/gl-pointcoord.html.ini | 194 + .../conformance/rendering/point-size.html.ini | 1 - ...-gl-pointcoord-in-fragment-shader.html.ini | 4 + .../misc/texture-upload-size.html.ini | 9 - ...ut-of-bounds-uniform-array-access.html.ini | 5 - .../out-of-bounds-uniform-array-access.html | 1 + tests/wpt/webgl/tools/timeout.patch | 12 + 3299 files changed, 40353 insertions(+), 93189 deletions(-) delete mode 100644 components/devtools/actors/browsing_context.rs delete mode 100644 components/devtools/actors/device.rs delete mode 100644 components/devtools/actors/emulation.rs delete mode 100644 components/devtools/actors/stylesheets.rs create mode 100644 components/devtools/actors/tab.rs delete mode 100644 components/layout/display_list/border.rs delete mode 100644 components/layout/display_list/gradient.rs delete mode 100644 components/net_traits/quality.rs delete mode 100644 components/pixels/Cargo.toml delete mode 100644 components/pixels/lib.rs create mode 100644 components/script/dom/htmltabledatacellelement.rs create mode 100644 components/script/dom/htmltableheadercellelement.rs delete mode 100644 components/script/dom/promiserejectionevent.rs delete mode 100644 components/script/dom/timeranges.rs delete mode 100644 components/script/dom/webgl_extensions/ext/extcolorbufferhalffloat.rs delete mode 100644 components/script/dom/webgl_extensions/ext/webglcolorbufferfloat.rs delete mode 100644 components/script/dom/webidls/EXTColorBufferHalfFloat.webidl create mode 100644 components/script/dom/webidls/HTMLTableDataCellElement.webidl create mode 100644 components/script/dom/webidls/HTMLTableHeaderCellElement.webidl delete mode 100644 components/script/dom/webidls/PromiseRejectionEvent.webidl delete mode 100644 components/script/dom/webidls/TimeRanges.webidl delete mode 100644 components/script/dom/webidls/WEBGLColorBufferFloat.webidl delete mode 100644 components/script/task_source/media_element.rs delete mode 100644 components/std_test_override/Cargo.toml delete mode 100644 components/std_test_override/lib.rs create mode 100644 components/style/gecko_bindings/sugar/ns_timing_function.rs delete mode 100644 components/style/values/animated/font.rs delete mode 100644 components/style/values/animated/length.rs delete mode 100644 components/style/values/animated/svg.rs delete mode 100644 components/style/values/computed/easing.rs delete mode 100644 components/style/values/generics/easing.rs delete mode 100644 components/style/values/generics/length.rs delete mode 100644 components/style/values/specified/easing.rs create mode 100755 etc/ci/bootstrap-android-and-accept-licences.sh create mode 100644 etc/ci/taskcluster/README.md create mode 100755 etc/ci/taskcluster/curl-artifact.sh create mode 100644 etc/ci/taskcluster/decision-task.py create mode 100644 etc/ci/taskcluster/decisionlib.py create mode 100644 etc/ci/taskcluster/docker/base.dockerfile create mode 100644 etc/ci/taskcluster/docker/build.dockerfile rename etc/{ => ci}/taskcluster/docker/run.dockerfile (100%) create mode 100755 etc/ci/taskcluster/mock.py mode change 100755 => 100644 etc/memory_reports_over_time.py delete mode 100644 etc/taskcluster/README.md delete mode 100644 etc/taskcluster/decision_task.py delete mode 100644 etc/taskcluster/decisionlib.py delete mode 100644 etc/taskcluster/docker/base.dockerfile delete mode 100644 etc/taskcluster/docker/build.dockerfile delete mode 100644 etc/taskcluster/docker/run-android-emulator.dockerfile delete mode 100755 etc/taskcluster/mock.py delete mode 100644 etc/taskcluster/packet.net/.gitignore delete mode 100644 etc/taskcluster/packet.net/README.md delete mode 100644 etc/taskcluster/packet.net/docker-worker.tf delete mode 100755 etc/taskcluster/packet.net/list_devices.py delete mode 100644 etc/taskcluster/packet.net/tc.py delete mode 100755 etc/taskcluster/packet.net/terraform_with_vars.py delete mode 100644 etc/taskcluster/windows/.gitignore delete mode 100644 etc/taskcluster/windows/README.md delete mode 100644 etc/taskcluster/windows/base-ami.txt delete mode 100644 etc/taskcluster/windows/bootstrap.ps1 delete mode 100755 etc/taskcluster/windows/build-ami.py delete mode 100644 etc/taskcluster/windows/first-boot.ps1 delete mode 100644 ports/libmlservo/Cargo.toml delete mode 100644 ports/libmlservo/src/lib.rs delete mode 100644 ports/servo/platform/macos/count_threads.c create mode 100644 support/android/apk/servoapp/src/main/java/com/mozilla/servo/MainActivity.java delete mode 100644 support/android/apk/servoapp/src/main/java/org/mozilla/servo/MainActivity.java create mode 100644 support/android/apk/servoview/src/main/java/com/mozilla/servoview/JNIServo.java create mode 100644 support/android/apk/servoview/src/main/java/com/mozilla/servoview/Servo.java create mode 100644 support/android/apk/servoview/src/main/java/com/mozilla/servoview/ServoSurface.java create mode 100644 support/android/apk/servoview/src/main/java/com/mozilla/servoview/ServoView.java delete mode 100644 support/android/apk/servoview/src/main/java/org/mozilla/servoview/JNIServo.java delete mode 100644 support/android/apk/servoview/src/main/java/org/mozilla/servoview/Servo.java delete mode 100644 support/android/apk/servoview/src/main/java/org/mozilla/servoview/ServoSurface.java delete mode 100644 support/android/apk/servoview/src/main/java/org/mozilla/servoview/ServoView.java delete mode 100644 support/magicleap/.gitignore delete mode 100644 support/magicleap/README.md delete mode 100644 support/magicleap/Servo2D/.vscode/launch.json delete mode 100644 support/magicleap/Servo2D/.vscode/settings.json delete mode 100644 support/magicleap/Servo2D/.vscode/tasks.json delete mode 100755 support/magicleap/Servo2D/Icon/Model/Model_UFO.fbx delete mode 100755 support/magicleap/Servo2D/Icon/Model/Model_UFO.kmat delete mode 100755 support/magicleap/Servo2D/Icon/Model/Model_UFO_Albedo.png delete mode 100755 support/magicleap/Servo2D/Icon/Model/Model_UFO_Albedo_Ring.png delete mode 100755 support/magicleap/Servo2D/Icon/Portal/InsidePortal_SkySphere.fbx delete mode 100755 support/magicleap/Servo2D/Icon/Portal/InsidePortal_SkySphere.kmat delete mode 100755 support/magicleap/Servo2D/Icon/Portal/InsidePortal_SkySphere.png delete mode 100644 support/magicleap/Servo2D/Servo2D.mabu delete mode 100644 support/magicleap/Servo2D/Servo2D.mlproject delete mode 100644 support/magicleap/Servo2D/Servo2D.package delete mode 100644 support/magicleap/Servo2D/code/inc.gen/SceneDescriptor.h delete mode 100644 support/magicleap/Servo2D/code/inc.gen/scenesGen.h delete mode 100644 support/magicleap/Servo2D/code/inc/Servo2D.h delete mode 100644 support/magicleap/Servo2D/code/src.gen/SceneDescriptor.cpp delete mode 100644 support/magicleap/Servo2D/code/src.gen/scenesGen.cpp delete mode 100644 support/magicleap/Servo2D/code/src/Servo2D.cpp delete mode 100644 support/magicleap/Servo2D/code/src/main.cpp delete mode 100644 support/magicleap/Servo2D/code/srcsGen.comp delete mode 100644 support/magicleap/Servo2D/fonts.xml delete mode 100644 support/magicleap/Servo2D/manifest.xml delete mode 100644 support/magicleap/Servo2D/pipeline/cache/AssetManifest.comp delete mode 100644 support/magicleap/Servo2D/pipeline/lap/project.json delete mode 100644 support/magicleap/Servo2D/scenes.comp delete mode 100644 support/magicleap/Servo2D/scenes/Servo2D.design delete mode 100644 support/magicleap/Servo2D/scenes/Servo2D.scene.res.xml delete mode 100644 support/magicleap/Servo2D/scenes/Servo2D.scene.xml delete mode 100755 support/magicleap/fake-ld.sh delete mode 100755 support/magicleap/openssl.sh delete mode 100644 support/magicleap/toolchain.cmake delete mode 100644 tests/unit/script/timeranges.rs delete mode 100644 tests/wpt/metadata/2dcontext/__dir__.ini delete mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/__dir__.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/canvas-createImageBitmap-resize.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/canvas-createImageBitmap-video-resize.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-bounds.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-drawImage.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-invalid-args.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-origin.sub.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-sizeOverflow.html.ini create mode 100644 tests/wpt/metadata/2dcontext/imagebitmap/createImageBitmap-transfer.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/pixel-manipulation/2d.imageData.create2.nonfinite.html.ini create mode 100644 tests/wpt/metadata/2dcontext/pixel-manipulation/2d.imageData.create2.zero.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/pixel-manipulation/2d.imageData.get.nonfinite.html.ini create mode 100644 tests/wpt/metadata/2dcontext/pixel-manipulation/2d.imageData.get.zero.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/pixel-manipulation/2d.imageData.put.nonfinite.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-colorManaged-convertToBlob-roundtrip.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-colorManaged-toBlob-toDataURL.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-colorspace-arguments.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-createImageBitmap-e_srgb.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-createPutGetImageData-colorManaged.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-draw-high-bit-depth-images.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-drawImage-e_srgb.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-drawImage-offscreenCanvas.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/canvas-getImageData-e_srgb.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/imageData-colorManagedBehavior.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/imageData-colorSpace.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/imagedata-no-color-settings-crash.html.ini delete mode 100644 tests/wpt/metadata/2dcontext/wide-gamut-canvas/transferFromImageBitmap.html.ini delete mode 100644 tests/wpt/metadata/cors/origin.htm.ini create mode 100644 tests/wpt/metadata/cors/redirect-userinfo.htm.ini delete mode 100644 tests/wpt/metadata/cors/request-headers.htm.ini delete mode 100644 tests/wpt/metadata/cors/status-async.htm.ini delete mode 100644 tests/wpt/metadata/cors/status-preflight.htm.ini delete mode 100644 tests/wpt/metadata/css/CSS2/abspos/abspos-in-block-in-inline-in-relpos-inline.html.ini delete mode 100644 tests/wpt/metadata/css/CSS2/abspos/adjacent-to-relpos-inline-in-inline-that-had-block.html.ini delete mode 100644 tests/wpt/metadata/css/CSS2/abspos/adjacent-to-relpos-inline-that-had-block.html.ini create mode 100644 tests/wpt/metadata/css/CSS2/borders/border-top-width-003.xht.ini create mode 100644 tests/wpt/metadata/css/CSS2/borders/groove-default.html.ini create mode 100644 tests/wpt/metadata/css/CSS2/borders/ridge-default.html.ini delete mode 100644 tests/wpt/metadata/css/CSS2/floats-clear/clear-on-parent-and-child.html.ini delete mode 100644 tests/wpt/metadata/css/CSS2/floats/computed-float-position-absolute.html.ini create mode 100644 tests/wpt/metadata/css/CSS2/text/text-indent-percent-001.xht.ini create mode 100644 tests/wpt/metadata/css/compositing/mix-blend-mode/mix-blend-mode-animation.html.ini delete mode 100644 tests/wpt/metadata/css/compositing/mix-blend-mode/mix-blend-mode-blended-with-transform-and-perspective.html.ini create mode 100644 tests/wpt/metadata/css/css-animations/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/css-animations/parsing/animation-delay-computed.html.ini delete mode 100644 tests/wpt/metadata/css/css-animations/parsing/animation-duration-computed.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-attachment-local/attachment-local-positioning-2.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-attachment-local/attachment-scroll-positioning-1.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-color-body-propagation-005.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-color-body-propagation-006.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-color-root-propagation-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/background-color-root-propagation-002.html.ini create mode 100644 tests/wpt/metadata/css/css-backgrounds/border-image-width-005.xht.ini create mode 100644 tests/wpt/metadata/css/css-backgrounds/border-image-width-006.xht.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/border-image-width-008.html.ini delete mode 100644 tests/wpt/metadata/css/css-backgrounds/scroll-positioned-multiple-background-images.html.ini delete mode 100644 tests/wpt/metadata/css/css-flexbox/dynamic-bsize-change.html.ini delete mode 100644 tests/wpt/metadata/css/css-flexbox/flex-minimum-height-flex-items-009.html.ini delete mode 100644 tests/wpt/metadata/css/css-flexbox/flex-minimum-height-flex-items-010.html.ini delete mode 100644 tests/wpt/metadata/css/css-fonts/font-feature-resolution-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-fonts/variations/font-descriptor-range-reversed.html.ini create mode 100644 tests/wpt/metadata/css/css-images/multiple-position-color-stop-linear.html.ini create mode 100644 tests/wpt/metadata/css/css-images/multiple-position-color-stop-radial.html.ini create mode 100644 tests/wpt/metadata/css/css-paint-api/geometry-border-image-002.https.html.ini create mode 100644 tests/wpt/metadata/css/css-paint-api/geometry-border-image-003.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-001.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-002.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-003.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-004.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-005.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-006.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-007.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-008.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-009.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-interpolation-010.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-invalidation-001.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-invalidation-002.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-stylemap.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-001.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-002.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-003.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-004.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-005.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-006.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-007.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-008.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-009.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-010.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-011.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-012.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-013.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-014.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-015.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-016.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-017.https.html.ini delete mode 100644 tests/wpt/metadata/css/css-paint-api/registered-property-value-018.https.html.ini create mode 100644 tests/wpt/metadata/css/css-text-decor/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/hanging-punctuation/hanging-scrollable-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/letter-spacing/letter-spacing-end-of-line-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/letter-spacing/letter-spacing-nesting-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/overflow-wrap/overflow-wrap-break-word-004.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/overflow-wrap/overflow-wrap-break-word-005.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/tab-size/tab-min-rendered-width-1.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/text-transform/text-transform-full-size-kana-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-000.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-002.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-003.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-004.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-005.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-006.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-007.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-008.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-00B.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-00D.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-00E.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-00F.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-010.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-011.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-012.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-013.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-014.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-015.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-016.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-017.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-018.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-019.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01A.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01B.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01C.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01D.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01E.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-01F.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-07F.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-080.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-081.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-082.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-083.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-084.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-085.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-086.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-087.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-088.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-089.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08A.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08B.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08C.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08D.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08E.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-08F.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-090.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-091.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-092.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-093.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-094.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-095.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-096.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-097.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-098.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-099.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09A.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09B.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09C.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09D.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09E.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/control-chars-09F.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/line-edge-white-space-collapse-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/line-edge-white-space-collapse-002.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/trailing-ideographic-space-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/trailing-ideographic-space-002.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/trailing-ideographic-space-004.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/white-space-empty-text-sibling.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-002.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-003.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/word-break/word-break-break-all-010.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/word-break/word-break-break-all-011.html.ini delete mode 100644 tests/wpt/metadata/css/css-text/word-break/word-break-keep-all-005.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/animation/list-interpolation.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/animation/matrix-interpolation.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/css-transforms-3d-on-anonymous-block-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/dynamic-fixed-pos-cb-change.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/css-transforms/transform-table-006.html.ini create mode 100644 tests/wpt/metadata/css/css-transitions/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/css-transitions/parsing/transition-duration-computed.html.ini delete mode 100644 tests/wpt/metadata/css/css-transitions/transition-timing-function-001.html.ini delete mode 100644 tests/wpt/metadata/css/css-transitions/transitionevent-interface.html.ini delete mode 100644 tests/wpt/metadata/css/css-ui/inheritance.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/CaretPosition-001.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementFromPoint-001.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementFromPoint-dynamic-anon-box.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-htb-ltr.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-htb-rtl.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-vlr-ltr.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-vlr-rtl.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-vrl-ltr.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-inline-vrl-rtl.html.ini create mode 100644 tests/wpt/metadata/css/cssom-view/elementsFromPoint-invalid-cases.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/getClientRects-br-htb-rtl.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/getClientRects-br-vlr-ltr.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/getClientRects-br-vlr-rtl.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/getClientRects-br-vrl-ltr.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/getClientRects-br-vrl-rtl.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/offsetTopLeftInline.html.ini delete mode 100644 tests/wpt/metadata/css/cssom-view/screenLeftTop.html.ini delete mode 100644 tests/wpt/metadata/css/filter-effects/parsing/backdrop-filter-computed.html.ini delete mode 100644 tests/wpt/metadata/css/filter-effects/parsing/backdrop-filter-parsing-valid.html.ini delete mode 100644 tests/wpt/metadata/css/filter-effects/parsing/filter-computed.html.ini delete mode 100644 tests/wpt/metadata/css/selectors/invalidation/where.html.ini delete mode 100644 tests/wpt/metadata/dom/events/shadow-relatedTarget.html.ini delete mode 100644 tests/wpt/metadata/dom/nodes/Node-insertBefore.html.ini delete mode 100644 tests/wpt/metadata/dom/nodes/Node-replaceChild.html.ini delete mode 100644 tests/wpt/metadata/domparsing/DOMParser-parseFromString-xml-parsererror.html.ini delete mode 100644 tests/wpt/metadata/eventsource/format-mime-trailing-semicolon.htm.ini create mode 100644 tests/wpt/metadata/fetch/api/redirect/redirect-origin.any.js.ini delete mode 100644 tests/wpt/metadata/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html.ini delete mode 100644 tests/wpt/metadata/fetch/nosniff/importscripts.html.ini delete mode 100644 tests/wpt/metadata/fetch/nosniff/parsing-nosniff.window.js.ini delete mode 100644 tests/wpt/metadata/fetch/nosniff/script.html.ini create mode 100644 tests/wpt/metadata/fetch/sec-metadata/report.tentative.https.sub.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/browsing-the-web/history-traversal/scroll-restoration-order.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/history/the-history-interface/traverse_the_history_1.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/history/the-history-interface/traverse_the_history_3.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/history/the-history-interface/traverse_the_history_write_after_load_2.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/history/the-history-interface/traverse_the_history_write_onload_2.html.ini delete mode 100644 tests/wpt/metadata/html/browsers/history/the-location-interface/no-browsing-context.window.js.ini delete mode 100644 tests/wpt/metadata/html/browsers/the-window-object/apis-for-creating-and-navigating-browsing-contexts-by-name/no_window_open_when_term_nesting_level_nonzero.window.js.ini delete mode 100644 tests/wpt/metadata/html/rendering/non-replaced-elements/flow-content-0/form-margin-quirk.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/non-replaced-elements/tables/transformed-tbody-tr-collapsed-border.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-block-margins-2.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-list-item-numbering.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/replaced-elements/the-select-element/select-1-block-size.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/replaced-elements/the-select-element/select-1-line-height.html.ini delete mode 100644 tests/wpt/metadata/html/rendering/replaced-elements/the-select-element/select-empty.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/document-metadata/the-link-element/link-style-error-limited-quirks.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/document-metadata/the-link-element/link-style-error-quirks.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/media-elements/loading-the-media-resource/load-events-networkState.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-insert-into-iframe.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-pause-networkState.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/media-elements/loading-the-media-resource/resource-selection-invoke-remove-from-document-networkState.html.ini create mode 100644 tests/wpt/metadata/html/semantics/embedded-content/media-elements/offsets-into-the-media-resource/currentTime.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/the-iframe-element/iframe-nosrc.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/the-img-element/decode/image-decode-with-quick-attach-svg.tentative.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/embedded-content/the-img-element/non-active-document.html.ini create mode 100644 tests/wpt/metadata/html/semantics/links/following-hyperlinks/activation-behavior.window.js.ini create mode 100644 tests/wpt/metadata/html/semantics/scripting-1/the-script-element/execution-timing/077.html.ini delete mode 100644 tests/wpt/metadata/html/semantics/scripting-1/the-script-element/module/dynamic-import/dynamic-imports-credentials.sub.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/001.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/005.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/008.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/009.https.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-02.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/document.open-03.html.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/readiness.window.js.ini create mode 100644 tests/wpt/metadata/html/webappapis/dynamic-markup-insertion/opening-the-input-stream/url-fragment.window.js.ini delete mode 100644 tests/wpt/metadata/html/webappapis/scripting/processing-model-2/unhandled-promise-rejections/disallow-crossorigin.html.ini create mode 100644 tests/wpt/metadata/quirks/unitless-length/no-quirks.html.ini create mode 100644 tests/wpt/metadata/quirks/unitless-length/quirks.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/child-css/external-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/child-css/internal-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/child-css/processing-instruction.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/font-face/external-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/font-face/external-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/font-face/internal-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/font-face/internal-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/font-face/processing-instruction.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/external-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/external-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/inline-style.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/internal-import-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/internal-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/presentation-attribute.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/image/processing-instruction.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/svg/external-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/svg/inline-style.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/svg/internal-stylesheet.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/svg/presentation-attribute.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/css-integration/svg/processing-instruction.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/generic/multiple-headers-and-values.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/generic/multiple-headers-combined.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/generic/multiple-headers-one-invalid.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/generic/multiple-headers-one-unknown-token.html.ini delete mode 100644 tests/wpt/metadata/referrer-policy/generic/multiple-headers.html.ini create mode 100644 tests/wpt/metadata/url/urlencoded-parser.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/jsapi/global/value-get-set.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/jsapi/idlharness.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/abort.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/body.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/contenttype.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/empty-body.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/idlharness.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/instantiateStreaming-bad-imports.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/instantiateStreaming.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/invalid-args.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/invalid-code.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/origin.sub.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/rejected-arg.any.js.ini delete mode 100644 tests/wpt/metadata/wasm/webapi/status.any.js.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-audiobuffersourcenode-interface/sample-accurate-scheduling.html.ini delete mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-postmessage-sharedarraybuffer.https.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-allpass.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-highpass.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-highshelf.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-lowpass.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-lowshelf.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-notch.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-peaking.html.ini create mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-biquadfilternode-interface/biquad-tail.html.ini delete mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/cors-check.https.html.ini delete mode 100644 tests/wpt/metadata/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/no-cors.https.html.ini delete mode 100644 tests/wpt/metadata/webstorage/event_constructor.html.ini create mode 100644 tests/wpt/metadata/xhr/access-control-and-redirects.htm.ini create mode 100644 tests/wpt/metadata/xhr/access-control-basic-allow-access-control-origin-header-data-url.htm.ini delete mode 100644 tests/wpt/metadata/xhr/allow-lists-starting-with-comma.htm.ini create mode 100644 tests/wpt/metadata/xhr/preserve-ua-header-on-redirect.htm.ini delete mode 100644 tests/wpt/metadata/xhr/responsexml-media-type.htm.ini create mode 100644 tests/wpt/metadata/xhr/send-accept-language.htm.ini delete mode 100644 tests/wpt/metadata/xhr/send-redirect-no-location.htm.ini create mode 100644 tests/wpt/metadata/xhr/setrequestheader-allow-empty-value.htm.ini create mode 100644 tests/wpt/metadata/xhr/setrequestheader-allow-whitespace-in-value.htm.ini delete mode 100644 tests/wpt/metadata/xhr/setrequestheader-combining.window.js.ini delete mode 100644 tests/wpt/metadata/xhr/status-async.htm.ini delete mode 100644 tests/wpt/metadata/xhr/status-basic.htm.ini delete mode 100644 tests/wpt/metadata/xhr/status-error.htm.ini create mode 100644 tests/wpt/mozilla/meta/css/border_black_ridge_a.html.ini create mode 100644 tests/wpt/mozilla/meta/css/border_black_ridge_b.html.ini delete mode 100644 tests/wpt/mozilla/meta/css/text_node_opacity.html.ini delete mode 100644 tests/wpt/mozilla/meta/mozilla/scrollBy.html.ini delete mode 100644 tests/wpt/mozilla/tests/mozilla/range_request_file_url.html delete mode 100644 tests/wpt/mozilla/tests/mozilla/resources/range.txt delete mode 100644 tests/wpt/mozilla/tests/mozilla/resources/range_small.txt delete mode 100644 tests/wpt/web-platform-tests/.azure-pipelines.yml delete mode 100644 tests/wpt/web-platform-tests/2dcontext/imagebitmap/createImageBitmap-blob-invalidtype.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/ImageData-fidelity.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-colorManaged-convertToBlob-roundtrip.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-colorManaged-toBlob-toDataURL.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-colorspace-arguments.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-createImageBitmap-e_srgb.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-createPutGetImageData-colorManaged.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-draw-high-bit-depth-images.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-drawImage-e_srgb.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-drawImage-offscreenCanvas.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/canvas-getImageData-e_srgb.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/imageData-colorManagedBehavior.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/imageData-colorSpace.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/imagedata-no-color-settings-crash.html delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-semitransparent-p3d65.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-semitransparent-rec2020.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-semitransparent-srgb.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb-fullcolor.ogv delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb-transparent.bmp delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb-transparent.ico delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb-transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb-transparent.webp delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.bmp delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.gif delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.ico delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.jpg delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.svg delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/pattern-srgb.webp delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_AdobeRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_AdobeRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_DisplayP3_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_DisplayP3_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_ProPhoto_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_ProPhoto_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_Rec2020_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_Rec2020_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_AdobeRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_AdobeRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_DisplayP3_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_DisplayP3_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_ProPhoto_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_ProPhoto_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_Rec2020_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_Rec2020_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_sRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_interlaced_sRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_sRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_16bit_sRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_AdobeRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_AdobeRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_DisplayP3_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_DisplayP3_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_ProPhoto_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_ProPhoto_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_Rec2020_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_Rec2020_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_sRGB_opaque.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/resources/png-16bit/2x2_8bit_sRGB_transparent.png delete mode 100644 tests/wpt/web-platform-tests/2dcontext/wide-gamut-canvas/transferFromImageBitmap.html delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/get-databases.any.js delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/key-generators/reading-autoincrement-common.js delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/key-generators/reading-autoincrement-indexes-cursors.any.js delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/key-generators/reading-autoincrement-indexes.any.js delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/key-generators/reading-autoincrement-store-cursors.any.js delete mode 100644 tests/wpt/web-platform-tests/IndexedDB/key-generators/reading-autoincrement-store.any.js delete mode 100644 tests/wpt/web-platform-tests/audio-output/setSinkId.html delete mode 100644 tests/wpt/web-platform-tests/background-fetch/abort.https.window.js delete mode 100644 tests/wpt/web-platform-tests/background-fetch/service_workers/sw-abort.js delete mode 100644 tests/wpt/web-platform-tests/beacon/beacon-error.sub.window.js create mode 100644 tests/wpt/web-platform-tests/beacon/beacon-error.window.js create mode 100644 tests/wpt/web-platform-tests/beacon/navigate.iFrame.sub.html delete mode 100644 tests/wpt/web-platform-tests/client-hints/image-with-dpr-header.html delete mode 100644 tests/wpt/web-platform-tests/client-hints/resources/dpr.py delete mode 100644 tests/wpt/web-platform-tests/client-hints/resources/square.png create mode 100644 tests/wpt/web-platform-tests/common/large.py delete mode 100644 tests/wpt/web-platform-tests/conformance-checkers/.gitignore create mode 100644 tests/wpt/web-platform-tests/conformance-checkers/html/elements/dl/aside-in-dt-novalid.html create mode 100644 tests/wpt/web-platform-tests/conformance-checkers/html/elements/input/pattern-asterisk-novalid.html create mode 100644 tests/wpt/web-platform-tests/conformance-checkers/html/elements/input/pattern-paren-novalid.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/304-response-should-update-csp.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/cspro-not-enforced-in-worker.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/cspro-not-enforced-in-worker.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/directive-name-case-insensitive.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/only-valid-whitespaces-are-allowed.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/support/304-response.py delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/support/eval.js delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/support/load_img_and_post_result_header.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/support/load_img_and_post_result_header.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/generic/support/load_img_and_post_result_meta.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/inheritance/blob-url-self-navigate-inherits.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/inheritance/support/navigate-self-to-blob.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/inheritance/support/navigate-self-to-blob.html.sub.headers create mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-allows-navigate-to-allows.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-allows-navigate-to-allows.sub.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-allows-navigate-to-blocks.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-allows-navigate-to-blocks.sub.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-blocks-navigate-to-allows.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-blocks-navigate-to-allows.sub.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-blocks-navigate-to-blocks.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/form-action/form-action-blocks-navigate-to-blocks.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/spv-only-sent-to-initiator.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/support/delayed_frame.py delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/support/spv-test-iframe1.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/support/spv-test-iframe1.sub.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/support/spv-test-iframe2.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/support/spv-test-iframe3.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/unsafe-allow-redirects/allowed-end-of-chain-because-of-same-origin.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/unsafe-allow-redirects/allowed-end-of-chain.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/navigate-to/unsafe-allow-redirects/blocked-end-of-chain.sub.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-2_1.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-2_1.html.sub.headers create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-2_2.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-2_2.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-no-url-allowed.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-no-url-allowed.html.sub.headers create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-no-url-allowed.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-no-url-blocked.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-no-url-blocked.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-allowed.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-allowed.html.sub.headers create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-allowed.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-blocked.html create mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-blocked.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-embed-allowed.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-embed-allowed.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-embed-blocked.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-redirect-allowed.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-redirect-allowed.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/object-src/object-src-url-redirect-blocked.sub.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/eval-allowed-in-report-only-mode-and-sends-report.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/eval-allowed-in-report-only-mode-and-sends-report.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/eval-allowed-in-report-only-mode.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/eval-allowed-in-report-only-mode.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-1.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-1.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-3.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-3.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-7.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-7.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-9.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/iso-8859-9.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/utf-8-lone-surrogate.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/utf-8-lone-surrogate.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/utf-8.html delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/script-src/hash-always-converted-to-utf-8/utf-8.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/content-security-policy/securitypolicyviolation/constructor-required-fields.html create mode 100644 tests/wpt/web-platform-tests/cookies/http-state/resources/test-files/disabled-chromium0023-expected create mode 100644 tests/wpt/web-platform-tests/cookies/http-state/resources/test-files/disabled-chromium0023-test create mode 100644 tests/wpt/web-platform-tests/cors/allow-headers.htm delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/abspos/abspos-in-block-in-inline-in-relpos-inline.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/abspos/adjacent-to-relpos-inline-in-inline-that-had-block.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/abspos/adjacent-to-relpos-inline-that-had-block.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/floats/computed-float-position-absolute.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-margin-bottom.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-margin-left.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-margin-right.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-margin-top.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-padding-bottom.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-padding-left.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-padding-right.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/normal-flow/containing-block-percent-padding-top.html delete mode 100644 tests/wpt/web-platform-tests/css/CSS2/positioning/absolute-non-replaced-height-013.html delete mode 100644 tests/wpt/web-platform-tests/css/css-animations/historical.html delete mode 100644 tests/wpt/web-platform-tests/css/css-animations/parsing/animation-delay-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/css-animations/parsing/animation-duration-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/background-color-body-propagation-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/background-color-body-propagation-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/background-color-body-propagation-006.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/background-color-root-propagation-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/background-color-root-propagation-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/border-image-width-008-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-backgrounds/border-image-width-008.html delete mode 100644 tests/wpt/web-platform-tests/css/css-conditional/at-supports-040.html delete mode 100644 tests/wpt/web-platform-tests/css/css-conditional/at-supports-041.html delete mode 100644 tests/wpt/web-platform-tests/css/css-conditional/at-supports-042.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/contain-layout-button-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/contain-layout-flexbox-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/contain-layout-grid-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/contain-paint-clip-019.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/contain-size-fieldset-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/reference/contain-layout-button-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/reference/contain-layout-flexbox-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/reference/contain-layout-grid-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/reference/contain-paint-clip-019-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-contain/reference/contain-size-fieldset-001-ref.html create mode 100644 tests/wpt/web-platform-tests/css/css-content/resources/blank.html delete mode 100644 tests/wpt/web-platform-tests/css/css-display/display-contents-shadow-host-whitespace.html delete mode 100644 tests/wpt/web-platform-tests/css/css-display/select-4-option-optgroup-display-none-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-display/select-4-option-optgroup-display-none.html delete mode 100644 tests/wpt/web-platform-tests/css/css-easing/META.yml delete mode 100644 tests/wpt/web-platform-tests/css/css-easing/cubic-bezier-timing-functions-output.html delete mode 100644 tests/wpt/web-platform-tests/css/css-easing/step-timing-functions-output.html delete mode 100644 tests/wpt/web-platform-tests/css/css-easing/step-timing-functions-syntax.html delete mode 100644 tests/wpt/web-platform-tests/css/css-exclusions/inheritance.html create mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/anonymous-flex-item-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/dynamic-bsize-change-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/dynamic-bsize-change.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/flex-minimum-height-flex-items-009.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/flex-minimum-height-flex-items-010.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/flex-minimum-height-flex-items-011.xht create mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/flexbox_empty-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-flexbox/percentage-heights-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-fonts/font-feature-resolution-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-fonts/font-feature-resolution-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-fonts/variations/font-descriptor-range-reversed-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-fonts/variations/font-descriptor-range-reversed.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-006.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-007.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-alignment-style-changes-008.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-gutters-013.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/alignment/grid-self-baseline-not-applied-if-sizing-cyclic-dependency-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/grid-items/grid-items-relative-offsets-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-grid/grid-items/grid-items-relative-offsets-002.html create mode 100644 tests/wpt/web-platform-tests/css/css-images/gradient-crash-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-images/multiple-position-color-stop-linear-2-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-images/multiple-position-color-stop-linear-2.html delete mode 100644 tests/wpt/web-platform-tests/css/css-images/multiple-position-color-stop-radial-2-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-images/multiple-position-color-stop-radial-2.html delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/clip-path/clip-path-inline-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/clip-path/clip-path-inline-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/clip-path/clip-path-inline-003.html create mode 100644 tests/wpt/web-platform-tests/css/css-masking/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/inheritance.sub.html delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/mask-negative-scale.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/mask-text-001.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/mask-type-001.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/mask-type-002.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/mask-type-003.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/reference/mask-green-square-001-ref.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/reference/mask-negative-scale-001-ref.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-masking/mask-svg-content/reference/mask-text-001-ref.svg delete mode 100644 tests/wpt/web-platform-tests/css/css-multicol/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-multicol/multicol-nested-006.html delete mode 100644 tests/wpt/web-platform-tests/css/css-multicol/multicol-under-vertical-rl-scroll-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-multicol/multicol-under-vertical-rl-scroll.html delete mode 100644 tests/wpt/web-platform-tests/css/css-overscroll-behavior/META.yml delete mode 100644 tests/wpt/web-platform-tests/css/css-overscroll-behavior/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-001.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-002.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-003.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-004.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-005.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-006.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-007.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-008.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-009.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-interpolation-010.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-invalidation-001.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-invalidation-002.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-stylemap.https.html create mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-type.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-001.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-002.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-003.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-004.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-005.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-006.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-007.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-008.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-009.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-010.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-011.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-012.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-013.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-014.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-015.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-016.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-017.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/registered-property-value-018.https.html delete mode 100644 tests/wpt/web-platform-tests/css/css-paint-api/resources/utils.js delete mode 100644 tests/wpt/web-platform-tests/css/css-position/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-position/position-sticky-child-multicolumn-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-position/position-sticky-child-multicolumn.html delete mode 100644 tests/wpt/web-platform-tests/css/css-properties-values-api/resources/utils.js delete mode 100644 tests/wpt/web-platform-tests/css/css-properties-values-api/self-utils.html delete mode 100644 tests/wpt/web-platform-tests/css/css-regions/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/host-context-specificity-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/host-context-specificity-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/host-context-specificity-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/host-specificity-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/shadow-host-removal-invalidation.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/shadow-reassign-dynamic-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/slotted-placeholder-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scoping/slotted-placeholder.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scroll-anchoring/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scroll-anchoring/text-anchor-in-vertical-rl.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scroll-snap/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-scrollbars/auto-scrollbar-inline-children.html delete mode 100644 tests/wpt/web-platform-tests/css/css-shapes/shape-outside/values/shape-outside-inset-0010.html delete mode 100644 tests/wpt/web-platform-tests/css/css-tables/caption-writing-mode-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/hanging-punctuation/hanging-scrollable-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/hanging-punctuation/reference/hanging-scrollable-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/letter-spacing-bidi-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/letter-spacing-bidi-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/letter-spacing-end-of-line-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/letter-spacing-nesting-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/letter-spacing-nesting-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/reference/letter-spacing-bidi-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/reference/letter-spacing-bidi-002-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/reference/letter-spacing-end-of-line-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/reference/letter-spacing-nesting-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/letter-spacing/reference/letter-spacing-nesting-002-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/overflow-wrap/overflow-wrap-break-word-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/overflow-wrap/overflow-wrap-break-word-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/tab-size/tab-min-rendered-width-1-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/tab-size/tab-min-rendered-width-1.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-indent/reference/text-indent-percentage-002-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-indent/text-indent-percentage-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-indent/text-indent-percentage-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-indent/text-indent-percentage-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-transform/reference/text-transform-full-size-kana-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-transform/reference/text-transform-full-size-kana-002-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-transform/text-transform-full-size-kana-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/text-transform/text-transform-full-size-kana-002.html create mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/break-spaces-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-000.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-006.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-007.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-008.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-00B.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-00D.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-00E.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-00F.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-010.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-011.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-012.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-013.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-014.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-015.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-016.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-017.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-018.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-019.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01A.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01B.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01C.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01D.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01E.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-01F.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-07F.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-080.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-081.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-082.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-083.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-084.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-085.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-086.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-087.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-088.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-089.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08A.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08B.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08C.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08D.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08E.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-08F.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-090.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-091.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-092.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-093.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-094.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-095.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-096.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-097.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-098.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-099.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09A.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09B.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09C.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09D.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09E.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/control-chars-09F.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/line-edge-white-space-collapse-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/line-edge-white-space-collapse-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/pre-wrap-015.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/control-chars-000-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/line-edge-white-space-collapse-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/line-edge-white-space-collapse-002-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/trailing-ideographic-space-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/trailing-ideographic-space-003-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/trailing-ideographic-space-004-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/trailing-ideographic-space-alt-003-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/white-space-pre-wrap-trailing-spaces-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/reference/white-space-pre-wrap-trailing-spaces-002-ref.html create mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/textarea-break-spaces-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/trailing-ideographic-space-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/trailing-ideographic-space-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/trailing-ideographic-space-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/trailing-ideographic-space-004.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/white-space-empty-text-sibling.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-002.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/white-space/white-space-pre-wrap-trailing-spaces-003.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/reference/word-break-break-all-010-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/reference/word-break-break-all-014-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/reference/word-break-break-all-020-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/reference/word-break-keep-all-005-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-break-all-010.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-break-all-011.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-break-all-014.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-break-all-020.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-keep-all-005.html delete mode 100644 tests/wpt/web-platform-tests/css/css-text/word-break/word-break-keep-all-006.html create mode 100644 tests/wpt/web-platform-tests/css/css-timing/META.yml create mode 100644 tests/wpt/web-platform-tests/css/css-timing/cubic-bezier-timing-functions-output.html create mode 100644 tests/wpt/web-platform-tests/css/css-timing/step-timing-functions-output.html rename tests/wpt/web-platform-tests/css/{css-easing => css-timing}/testcommon.js (100%) delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/animation/list-interpolation.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/animation/matrix-interpolation.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/dynamic-fixed-pos-cb-change-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/dynamic-fixed-pos-cb-change.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transforms/text-perspective-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transitions/parsing/transition-duration-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/css-transitions/transitionevent-interface.html delete mode 100644 tests/wpt/web-platform-tests/css/css-ui/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/css-will-change/will-change-abspos-cb-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/css-will-change/will-change-abspos-cb-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-will-change/will-change-abspos-cb-dynamic-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-will-change/will-change-inherit-dynamic.html delete mode 100644 tests/wpt/web-platform-tests/css/css-writing-modes/inline-box-border-vlr-001.html delete mode 100644 tests/wpt/web-platform-tests/css/css-writing-modes/reference/inline-box-border-vlr-001.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-htb-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-htb-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-vlr-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-vlr-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-vrl-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/elementsFromPoint-inline-vrl-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-htb-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-htb-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-vlr-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-vlr-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-vrl-ltr.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-br-vrl-rtl.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/getClientRects-inline.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/offsetTopLeftInline.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom-view/screenLeftTop.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom/cssstyledeclaration-mutationrecord-005.html delete mode 100644 tests/wpt/web-platform-tests/css/cssom/cssstyledeclaration-setter-attr.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/filter-scale-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/filter-scale-001.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/filter-scaling-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/filter-scaling-001.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/parsing/backdrop-filter-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/parsing/backdrop-filter-parsing-invalid.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/parsing/backdrop-filter-parsing-valid.html delete mode 100644 tests/wpt/web-platform-tests/css/filter-effects/parsing/filter-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/motion/inheritance.html delete mode 100644 tests/wpt/web-platform-tests/css/motion/parsing/offset-rotate-computed.html delete mode 100644 tests/wpt/web-platform-tests/css/reference/blank.html delete mode 100644 tests/wpt/web-platform-tests/css/reference/pass_if_two_words.html delete mode 100644 tests/wpt/web-platform-tests/css/selectors/floating-first-letter-05d0.html delete mode 100644 tests/wpt/web-platform-tests/css/selectors/floating-first-letter-feff.html delete mode 100644 tests/wpt/web-platform-tests/css/selectors/floating-first-letter-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/selectors/invalidation/where.html delete mode 100644 tests/wpt/web-platform-tests/css/selectors/selector-placeholder-shown-emptify-placeholder.html delete mode 100644 tests/wpt/web-platform-tests/css/support/computed-testcommon.js delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/contain/contain-layout-ignored-cases-ib-split-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/contain/contain-layout-ignored-cases-ib-split-001.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/contain/contain-paint-ignored-cases-ib-split-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/contain/contain-paint-ignored-cases-ib-split-001.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-dyn-resize-001-ref.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/flexbox/flexbox-dyn-resize-001.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-1-ref.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-1.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2-ref.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2a.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2b.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2c.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2d.html create mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/transforms/individual-transform-2e.html delete mode 100644 tests/wpt/web-platform-tests/css/vendor-imports/mozilla/mozilla-central-reftests/values3/support/blue-32x32.png delete mode 100644 tests/wpt/web-platform-tests/docs/_admin/index.md delete mode 100644 tests/wpt/web-platform-tests/docs/_includes/svg/octicons/key.svg delete mode 100644 tests/wpt/web-platform-tests/docs/_reviewing-tests/email.md delete mode 100644 tests/wpt/web-platform-tests/dom/events/Event-dispatch-on-disabled-elements.html delete mode 100644 tests/wpt/web-platform-tests/dom/events/shadow-relatedTarget.html delete mode 100644 tests/wpt/web-platform-tests/dom/nodes/pre-insertion-checks.js delete mode 100644 tests/wpt/web-platform-tests/domparsing/DOMParser-parseFromString-xml-parsererror.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/layout-animations-disabled-tentative.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/layout-animations-disabled-tentative.html.headers delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/layout-animations-enabled-tentative.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/lazyload/lazyload-disabled-image-tentative.sub.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/lazyload/lazyload-disabled-image-tentative.sub.html.headers delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/lazyload/lazyload-enabled-image-tentative.sub.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/lazyload/lazyload-image-attribute-on-sanity-check-tentative.sub.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/resources/lazyload.png delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/resources/vertical-scroll-scrollable-content.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/resources/vertical-scroll-scrollbar-ref.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/vertical-scroll-disabled-frame-no-scroll-manual.tentative.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/experimental-features/vertical-scroll-disabled-scrollbar-tentative.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/feature-policy-header-policy-declined.https.sub.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/feature-policy-header-policy-declined.https.sub.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/encrypted-media-reporting.https.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/encrypted-media-reporting.https.html.headers delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/generic-sensor-reporting.https.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/generic-sensor-reporting.https.html.headers delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/picture-in-picture-reporting.html delete mode 100644 tests/wpt/web-platform-tests/feature-policy/reporting/picture-in-picture-reporting.html.headers delete mode 100644 tests/wpt/web-platform-tests/fetch/corb/resources/sniffable-resource.py delete mode 100644 tests/wpt/web-platform-tests/fetch/corb/script-resource-with-json-parser-breaker.tentative.sub.html create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/parsing-nosniff.html delete mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/parsing-nosniff.window.js create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-first.asis create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-last.asis create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-no-x.asis create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-quoted-single.asis create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-quoted.asis create mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff-uppercase.asis delete mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/nosniff.py delete mode 100644 tests/wpt/web-platform-tests/fetch/nosniff/resources/x-content-type-options.json delete mode 100644 tests/wpt/web-platform-tests/fetch/redirect-navigate/302-found-post-handler.py delete mode 100644 tests/wpt/web-platform-tests/fetch/redirect-navigate/302-found-post.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/browsing-the-web/history-traversal/scroll-restoration-order.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/history/the-history-interface/blank-new.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/history/the-history-interface/blank-old.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/history/the-history-interface/iframe_history_go_0.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/history/the-location-interface/no-browsing-context.window.js delete mode 100644 tests/wpt/web-platform-tests/html/browsers/offline/appcache/appcache-iframe.https.html delete mode 100644 tests/wpt/web-platform-tests/html/browsers/offline/appcache/resources/appcache-data.py delete mode 100644 tests/wpt/web-platform-tests/html/browsers/offline/appcache/resources/appcache-iframe.manifest delete mode 100644 tests/wpt/web-platform-tests/html/browsers/offline/appcache/resources/appcache-iframe.py delete mode 100644 tests/wpt/web-platform-tests/html/browsers/the-window-object/apis-for-creating-and-navigating-browsing-contexts-by-name/no_window_open_when_term_nesting_level_nonzero.window.js delete mode 100644 tests/wpt/web-platform-tests/html/editing/dnd/resources/32mb.py delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/flow-content-0/form-margin-quirk.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/tables/transformed-tbody-tr-collapsed-border-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/tables/transformed-tbody-tr-collapsed-border.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-block-margins-2-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-block-margins-2.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-list-item-numbering-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/non-replaced-elements/the-fieldset-and-legend-elements/legend-list-item-numbering.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-1-block-size-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-1-block-size.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-1-line-height-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-1-line-height.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-empty-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/rendering/replaced-elements/the-select-element/select-empty.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/document-metadata/the-link-element/link-style-error-limited-quirks.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/document-metadata/the-link-element/link-style-error-quirks.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/document-metadata/the-link-element/resources/css.py delete mode 100644 tests/wpt/web-platform-tests/html/semantics/document-metadata/the-link-element/resources/link-style-error.js delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-iframe-element/iframe-nosrc.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-img-element/available-images-ref.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-img-element/available-images.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-img-element/decode/image-decode-with-quick-attach-svg.tentative.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-object-element/object-fallback-failed-cross-origin-navigation.sub.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/embedded-content/the-video-element/intrinsic_sizes.htm delete mode 100644 tests/wpt/web-platform-tests/html/semantics/forms/form-submission-target/form-target-iframe-helper.py delete mode 100644 tests/wpt/web-platform-tests/html/semantics/forms/form-submission-target/form-target-iframe.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/forms/the-legend-element/HTMLLegendElement.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/dynamic-imports-credentials.sub.html delete mode 100644 tests/wpt/web-platform-tests/html/semantics/scripting-1/the-script-element/module/resources/dynamic-import-credentials-iframe.sub.html delete mode 100644 tests/wpt/web-platform-tests/html/webappapis/system-state-and-capabilities/the-navigator-object/navigatorcookies-cookieenabled-false-manual.html delete mode 100644 tests/wpt/web-platform-tests/html/webappapis/system-state-and-capabilities/the-navigator-object/navigatorcookies-cookieenabled-true.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/assumptions/allowed-to-play.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/assumptions/blank.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/assumptions/cookie.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/assumptions/allowed-to-play.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/assumptions/html-elements.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/server/context.any.js.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/server/order-of-metas.any.js.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/server/secure-context.https.any.js.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/server/title.any.js.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/elementPosition.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/elementTiming.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/eventOrder.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/metadata/infrastructure/testdriver/actions/multiDevice.html.ini delete mode 100644 tests/wpt/web-platform-tests/infrastructure/testdriver/actions/elementPosition.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/testdriver/actions/elementTiming.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/testdriver/actions/eventOrder.html delete mode 100644 tests/wpt/web-platform-tests/infrastructure/testdriver/actions/multiDevice.html delete mode 100644 tests/wpt/web-platform-tests/interfaces/wasm-web-api.idl delete mode 100644 tests/wpt/web-platform-tests/intersection-observer/target-in-different-window.html delete mode 100644 tests/wpt/web-platform-tests/media-capabilities/encodingInfo.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-record/MediaRecorder-destroy-script-execution.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-record/MediaRecorder-error.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-record/MediaRecorder-stop.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-record/support/MediaRecorder-iframe.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-streams/MediaDevices-SecureContext.html delete mode 100644 tests/wpt/web-platform-tests/mediacapture-streams/MediaStream-clone.https.html delete mode 100644 tests/wpt/web-platform-tests/navigation-timing/dom_interactive_image_document.html delete mode 100644 tests/wpt/web-platform-tests/navigation-timing/dom_interactive_media_document.html delete mode 100644 tests/wpt/web-platform-tests/orientation-event/ondeviceorientationabsolute.html delete mode 100644 tests/wpt/web-platform-tests/payment-method-basic-card/historical.https.html delete mode 100644 tests/wpt/web-platform-tests/payment-method-id/payment-request-ctor-pmi-handling.https.html create mode 100644 tests/wpt/web-platform-tests/payment-request/PaymentItem/type_member.https.html delete mode 100644 tests/wpt/web-platform-tests/payment-request/payment-request-canmakepayment-method-protection.https.html delete mode 100644 tests/wpt/web-platform-tests/permissions/test-background-fetch-permission.html delete mode 100644 tests/wpt/web-platform-tests/pointerevents/extension/pointerevent_getPredictedEvents_when_pointerlocked-manual.html delete mode 100644 tests/wpt/web-platform-tests/pointerevents/extension/pointerevent_predicted_events_attributes-manual.html delete mode 100644 tests/wpt/web-platform-tests/quirks/reference/vertical-align-in-quirks-ref.html delete mode 100644 tests/wpt/web-platform-tests/quirks/vertical-align-in-quirks.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/child-css/external-import-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/child-css/internal-import-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/child-css/processing-instruction.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/css-test-helper.js create mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/external-import-stylesheet.html rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/external-stylesheet.html (100%) delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/font-face/external-import-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/font-face/external-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/font-face/internal-import-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/font-face/internal-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/font-face/processing-instruction.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/image/external-import-stylesheet.html rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/inline-style.html (100%) rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/internal-import-stylesheet.html (100%) rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/internal-stylesheet.html (100%) rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/presentation-attribute.html (100%) rename tests/wpt/web-platform-tests/referrer-policy/css-integration/{image => }/processing-instruction.html (100%) delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/svg/external-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/svg/inline-style.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/svg/internal-stylesheet.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/svg/presentation-attribute.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/css-integration/svg/processing-instruction.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-and-values.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-and-values.html.headers delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-combined.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-combined.html.headers delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-one-invalid.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-one-invalid.html.headers delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-one-unknown-token.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers-one-unknown-token.html.headers delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers.html delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/multiple-headers.html.headers delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/subresource/font.py delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/subresource/svg.py delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/template/font.css.template rename tests/wpt/web-platform-tests/referrer-policy/generic/template/{image.css.template => stylesheet.css.template} (100%) delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/template/svg.css.template delete mode 100644 tests/wpt/web-platform-tests/referrer-policy/generic/template/svg.embedded.template delete mode 100644 tests/wpt/web-platform-tests/resources/chromium/url.mojom.js delete mode 100644 tests/wpt/web-platform-tests/resources/test/tests/functional/log-insertion.html delete mode 100644 tests/wpt/web-platform-tests/resources/test/tests/unit/IdlInterface/get_interface_object.html delete mode 100644 tests/wpt/web-platform-tests/resources/test/tests/unit/IdlInterface/get_interface_object_owner.html delete mode 100644 tests/wpt/web-platform-tests/resources/test/tests/unit/IdlInterface/get_legacy_namespace.html delete mode 100644 tests/wpt/web-platform-tests/resources/test/tests/unit/IdlInterface/get_qualified_name.html delete mode 100644 tests/wpt/web-platform-tests/resources/testdriver-actions.js delete mode 100644 tests/wpt/web-platform-tests/selection/addRange.tentative.html delete mode 100644 tests/wpt/web-platform-tests/selection/stringifier.tentative.html create mode 100644 tests/wpt/web-platform-tests/server-timing/cross_origin.html delete mode 100644 tests/wpt/web-platform-tests/server-timing/cross_origin.https.html rename tests/wpt/web-platform-tests/server-timing/{idlharness.https.any.js => idlharness.any.js} (100%) create mode 100644 tests/wpt/web-platform-tests/server-timing/navigation_timing_idl.html create mode 100644 tests/wpt/web-platform-tests/server-timing/resource_timing_idl.html create mode 100644 tests/wpt/web-platform-tests/server-timing/server_timing_header-parsing.html create mode 100644 tests/wpt/web-platform-tests/server-timing/test_server_timing.html create mode 100644 tests/wpt/web-platform-tests/server-timing/test_server_timing.html.sub.headers delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/fetch-audio-tainting.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/import-module-scripts.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/import-scripts-mime-types.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/postmessage-to-client-message-queue.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/enable-client-message-queue.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/import-scripts-mime-types-worker.js delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/imported-classic-script.js delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/imported-module-script.js delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/message-vs-microtask.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/nested-iframe-parent.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/stalling-service-worker.js delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/update-during-installation-worker.js delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/update-missing-import-scripts-imported-worker.py delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/update-missing-import-scripts-main-worker.py delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/resources/update-registration-with-type.py delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/update-missing-import-scripts.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/update-not-allowed.https.html delete mode 100644 tests/wpt/web-platform-tests/service-workers/service-worker/update-registration-with-type.https.html delete mode 100644 tests/wpt/web-platform-tests/shadow-dom/slots-outside-shadow-dom.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/META.yml delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/README.md delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/fallback-to-another-sxg.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/nested-sxg.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/127.0.0.1.sxg.ext delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/127.0.0.1.sxg.key delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/127.0.0.1.sxg.pem delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/127.0.0.1.sxg.pem.cbor delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/127.0.0.1.sxg.pem.cbor.headers delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/failure.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/fallback-to-another-sxg.sxg delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/fallback-to-another-sxg.sxg.headers delete mode 100755 tests/wpt/web-platform-tests/signed-exchange/resources/generate-test-certs.sh delete mode 100755 tests/wpt/web-platform-tests/signed-exchange/resources/generate-test-sxgs.sh delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/inner-url.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/nested-sxg.sxg delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/nested-sxg.sxg.headers delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-invalid-validity-url.sxg delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-invalid-validity-url.sxg.headers delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-location.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-location.sxg delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-location.sxg.headers delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/resources/sxg-util.js delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-double-prefetch.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-fallback-with-fragment.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-invalid-validity-url.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-location-fragment.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-location.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-non-secure-origin.tentative.html delete mode 100644 tests/wpt/web-platform-tests/signed-exchange/sxg-prefetch-resource-timing.tentative.html delete mode 100644 tests/wpt/web-platform-tests/speech-api/SpeechSynthesisErrorEvent-constructor.html delete mode 100644 tests/wpt/web-platform-tests/speech-api/SpeechSynthesisEvent-constructor.html delete mode 100644 tests/wpt/web-platform-tests/streams/piping/abort.dedicatedworker.html delete mode 100644 tests/wpt/web-platform-tests/streams/piping/abort.html delete mode 100644 tests/wpt/web-platform-tests/streams/piping/abort.js delete mode 100644 tests/wpt/web-platform-tests/streams/piping/abort.serviceworker.https.html delete mode 100644 tests/wpt/web-platform-tests/streams/piping/abort.sharedworker.html delete mode 100644 tests/wpt/web-platform-tests/svg/interact/inheritance.svg delete mode 100644 tests/wpt/web-platform-tests/svg/interact/parsing/pointer-events-invalid.svg delete mode 100644 tests/wpt/web-platform-tests/svg/interact/parsing/pointer-events-valid.svg delete mode 100644 tests/wpt/web-platform-tests/svg/linking/reftests/use-hidden-attr-change.html delete mode 100644 tests/wpt/web-platform-tests/svg/render/reftests/filter-effects-on-pattern-ref.html delete mode 100644 tests/wpt/web-platform-tests/svg/render/reftests/filter-effects-on-pattern.html delete mode 100644 tests/wpt/web-platform-tests/svg/shapes/circle-01-ref.svg delete mode 100644 tests/wpt/web-platform-tests/svg/shapes/circle-01.svg delete mode 100644 tests/wpt/web-platform-tests/svg/shapes/ellipse-09.svg delete mode 100644 tests/wpt/web-platform-tests/svg/shapes/rect-05-ref.svg delete mode 100644 tests/wpt/web-platform-tests/svg/shapes/rect-05.svg delete mode 100644 tests/wpt/web-platform-tests/svg/types/scripted/SVGGeometryElement.isPointInFill-01.svg delete mode 100644 tests/wpt/web-platform-tests/svg/types/scripted/SVGGeometryElement.isPointInStroke-01.svg create mode 100644 tests/wpt/web-platform-tests/tools/appveyor.yml create mode 100644 tests/wpt/web-platform-tests/tools/flake8.ini rename tests/wpt/web-platform-tests/tools/lint/tests/dummy/{about_blank.html => ref/about_blank-ref.html} (100%) delete mode 100644 tests/wpt/web-platform-tests/tools/py27-flake8.ini delete mode 100644 tests/wpt/web-platform-tests/tools/py36-flake8.ini delete mode 100644 tests/wpt/web-platform-tests/tools/requirements_flake8.txt create mode 100644 tests/wpt/web-platform-tests/tools/runner/logo.svg delete mode 100644 tests/wpt/web-platform-tests/tools/wpt/tests/test_browser.py create mode 100644 tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/chrome_webdriver.py delete mode 100644 tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/executors/runner.js create mode 100644 tests/wpt/web-platform-tests/tools/wptserve/.travis.yml delete mode 100644 tests/wpt/web-platform-tests/trusted-types/TrustedTypePolicyFactory-createPolicy-cspTests-wildcard.tentative.html delete mode 100644 tests/wpt/web-platform-tests/trusted-types/TrustedTypePolicyFactory-createPolicy-defaultTests.tentative.html delete mode 100644 tests/wpt/web-platform-tests/trusted-types/TrustedTypePolicyFactory-isXXX.tentative.html create mode 100644 tests/wpt/web-platform-tests/wasm/idlharness.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/jsapi/global/value-get-set.any.js create mode 100644 tests/wpt/web-platform-tests/wasm/jsapi/global/value-set.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/jsapi/idlharness.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/abort.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/body.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/contenttype.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/empty-body.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/idlharness.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/instantiateStreaming-bad-imports.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/instantiateStreaming.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/invalid-args.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/invalid-code.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/origin.sub.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/rejected-arg.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/status.any.js delete mode 100644 tests/wpt/web-platform-tests/wasm/webapi/status.py delete mode 100644 tests/wpt/web-platform-tests/webaudio/js/worklet-recorder.js delete mode 100644 tests/wpt/web-platform-tests/webaudio/resources/4ch-440.wav delete mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-audiobuffer-interface/audiobuffer-reuse.html rename tests/wpt/web-platform-tests/webaudio/the-audio-api/the-audiobuffersourcenode-interface/{resources => }/audiobuffersource-multi-channels-expected.wav (100%) delete mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/audioworklet-postmessage-sharedarraybuffer.https.html delete mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-audioworklet-interface/processors/sharedarraybuffer-processor.js create mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-gainnode-interface/gain-expected.wav delete mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/cors-check.https.html delete mode 100644 tests/wpt/web-platform-tests/webaudio/the-audio-api/the-mediaelementaudiosourcenode-interface/no-cors.https.html rename tests/wpt/web-platform-tests/webdriver/tests/{get_page_source => actions}/__init__.py (100%) create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/conftest.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/control_click.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/key.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/key_shortcuts.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/modifier_click.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/mouse.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/mouse_dblclick.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/mouse_pause_dblclick.py rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/none.py (100%) create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/pointer_origin.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/sequence.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/actions/special_keys.py rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions/support}/__init__.py (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/support/keys.py (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/support/mouse.py (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/support/refine.py (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/support/test_actions_wdspec.html (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions => actions}/validity.py (100%) delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/add_cookie/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/delete_all_cookies/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/element_clear/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/element_click/center_point.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/element_click/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/execute_script/promise.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/find_element/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/find_element_from_element/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/find_elements/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/find_elements_from_element/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/get_active_element/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/get_element_attribute/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/get_element_text/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/get_named_cookie/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/get_page_source/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/navigate_to/user_prompts.py rename tests/wpt/web-platform-tests/webdriver/tests/{perform_actions/support => page_source}/__init__.py (100%) rename tests/wpt/web-platform-tests/webdriver/tests/{get_page_source => page_source}/source.py (100%) delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/conftest.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/key.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/key_events.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/key_modifiers.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/key_shortcuts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/key_special_keys.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_contextmenu.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_dblclick.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_modifier_click.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_origin.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/pointer_pause_dblclick.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/sequence.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/perform_actions/user_prompts.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/__init__.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/conftest.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/release.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/sequence.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/support/__init__.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/support/refine.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/release_actions/support/test_actions_wdspec.html delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/support/fixtures.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/support/image.py delete mode 100644 tests/wpt/web-platform-tests/webdriver/tests/support/sync.py create mode 100644 tests/wpt/web-platform-tests/webdriver/tests/support/wait.py rename tests/wpt/web-platform-tests/webmessaging/with-options/{broken-origin.html => broken-origin.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{host-specific-origin.html => host-specific-origin.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{message-channel-transferable.html => message-channel-transferable.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{no-target-origin.html => no-target-origin.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{null-transfer.html => null-transfer.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{one-arg.html => one-arg.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{slash-origin.html => slash-origin.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{undefined-transferable.html => undefined-transferable.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmessaging/with-options/{unknown-parameter.html => unknown-parameter.tentative.html} (100%) rename tests/wpt/web-platform-tests/webmidi/{idlharness.https.window.js => idlharness.window.js} (100%) delete mode 100644 tests/wpt/web-platform-tests/webrtc-identity/META.yml delete mode 100644 tests/wpt/web-platform-tests/webrtc-identity/RTCPeerConnection-constructor.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/RTCCertificate-postMessage.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/RTCIceTransport-extension-helper.js create mode 100644 tests/wpt/web-platform-tests/webrtc/RTCPeerConnection-createOffer-offerToReceive.html rename tests/wpt/web-platform-tests/{webrtc-identity => webrtc}/RTCPeerConnection-getIdentityAssertion.sub.html (100%) rename tests/wpt/web-platform-tests/{webrtc-identity => webrtc}/RTCPeerConnection-peerIdentity.html (100%) delete mode 100644 tests/wpt/web-platform-tests/webrtc/RTCPeerConnection-remote-track-mute.https.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/RTCRtpTransceiver-direction.html create mode 100644 tests/wpt/web-platform-tests/webrtc/RTCRtpTransceiver-setDirection.html rename tests/wpt/web-platform-tests/{webrtc-identity => webrtc}/identity-helper.sub.js (100%) delete mode 100644 tests/wpt/web-platform-tests/webrtc/legacy/README.txt delete mode 100644 tests/wpt/web-platform-tests/webrtc/legacy/RTCPeerConnection-createOffer-offerToReceive.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/legacy/RTCRtpTransceiver-with-OfferToReceive-options.https.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/legacy/onaddstream.https.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/protocol/jsep-initial-offer.https.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/resources/RTCCertificate-postMessage-iframe.html delete mode 100644 tests/wpt/web-platform-tests/webrtc/simplecall-no-ssrcs.https.html create mode 100644 tests/wpt/web-platform-tests/webstorage/event_constructor_eventinit.html delete mode 100644 tests/wpt/web-platform-tests/webstorage/event_initstorageevent.html create mode 100644 tests/wpt/web-platform-tests/webstorage/event_local_storageeventinit.html create mode 100644 tests/wpt/web-platform-tests/webstorage/event_session_storageeventinit.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_50-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_50.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_gt_50-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_gt_50.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_lt_50-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_lt_50.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_lt_50_size_gt_maximum_size-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_position_lt_50_size_gt_maximum_size.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_wrapped-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_center_wrapped.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_50-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_50.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_gt_50-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_gt_50.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_lt_50-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_lt_50.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_lt_50_size_gt_maximum_size-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_position_lt_50_size_gt_maximum_size.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_wrapped-ref.html create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/align_middle_wrapped.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/basic-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/basic.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/regionanchor_x_50_percent-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/regionanchor_x_50_percent.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/regionanchor_y_50_percent-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/regionanchor_y_50_percent.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/scroll_up-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/scroll_up.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/single_line_top_left-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/single_line_top_left.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/basic.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/regionanchor_x_50_percent.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/regionanchor_y_50_percent.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/scroll_up.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/single_line_top_left.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/viewportanchor_x_50_percent.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/viewportanchor_y_50_percent.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/support/width_50_percent.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/viewportanchor_x_50_percent-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/viewportanchor_x_50_percent.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/viewportanchor_y_50_percent-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/viewportanchor_y_50_percent.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/width_50_percent-ref.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/regions/width_50_percent.html delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center_long.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center_position_50.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center_position_gt_50.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center_position_lt_50.vtt delete mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_center_position_lt_50_size_gt_maximum_size.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle_long.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle_position_50.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle_position_gt_50.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle_position_lt_50.vtt create mode 100644 tests/wpt/web-platform-tests/webvtt/rendering/cues-with-video/processing-model/support/align_middle_position_lt_50_size_gt_maximum_size.vtt delete mode 100644 tests/wpt/web-platform-tests/workers/modules/resources/dynamic-import-remote-origin-credentials-checker-worker.sub.js delete mode 100644 tests/wpt/web-platform-tests/workers/modules/resources/dynamic-import-same-origin-credentials-checker-worker.js delete mode 100644 tests/wpt/web-platform-tests/workers/modules/resources/static-import-remote-origin-credentials-checker-worker.sub.js delete mode 100644 tests/wpt/web-platform-tests/workers/modules/resources/static-import-same-origin-credentials-checker-worker.js delete mode 100644 tests/wpt/web-platform-tests/xhr/overridemimetype-unsent-state-force-shiftjis.any.js create mode 100644 tests/wpt/web-platform-tests/xhr/overridemimetype-unsent-state-force-shiftjis.htm delete mode 100755 tests/wpt/web-platform-tests/xhr/resources/header-content-length-twice.asis delete mode 100644 tests/wpt/web-platform-tests/xhr/resources/headers-double-empty.asis delete mode 100644 tests/wpt/web-platform-tests/xhr/resources/headers-some-are-empty.asis delete mode 100644 tests/wpt/web-platform-tests/xhr/setrequestheader-combining.window.js create mode 100644 tests/wpt/webgl/meta/conformance/extensions/oes-texture-float.html.ini create mode 100644 tests/wpt/webgl/meta/conformance/glsl/variables/gl-pointcoord.html.ini create mode 100644 tests/wpt/webgl/meta/conformance/rendering/point-with-gl-pointcoord-in-fragment-shader.html.ini delete mode 100644 tests/wpt/webgl/meta/conformance/uniforms/out-of-bounds-uniform-array-access.html.ini diff --git a/.gitignore b/.gitignore index 55bd1fc1ce4d..94acd5b1d033 100644 --- a/.gitignore +++ b/.gitignore @@ -19,7 +19,6 @@ *.csv *.rej *.orig -.coverage .DS_Store Servo.app .config.mk.last diff --git a/.taskcluster.yml b/.taskcluster.yml index 7087419c4737..5af791d6b8fc 100644 --- a/.taskcluster.yml +++ b/.taskcluster.yml @@ -5,7 +5,7 @@ policy: tasks: - $if: 'tasks_for == "github-push"' then: - $if: 'event.ref in ["refs/heads/auto", "refs/heads/try", "refs/heads/try-taskcluster"]' + $if: 'event.ref in ["refs/heads/auto", "refs/heads/try"]' then: # NOTE: when updating this consider whether the daily hook needs similar changes: @@ -23,8 +23,12 @@ tasks: owner: &task_owner ${event.pusher.name}@users.noreply.github.com source: &task_source ${event.compare} scopes: + - "queue:scheduler-id:taskcluster-github" + # Granted to role "repo:github.com/servo/servo:branch:*" - - "assume:project:servo:decision-task/trusted" + - "queue:create-task:highest:aws-provisioner-v1/servo-*" + - "queue:route:index.project.servo.servo.*" + - "docker-worker:cache:cargo-*" payload: maxRunTime: {$eval: '20 * 60'} @@ -49,4 +53,4 @@ tasks: cd repo && git fetch --depth 1 "$GIT_URL" "$GIT_REF" && git reset --hard "$GIT_SHA" && - python3 etc/taskcluster/decision_task.py + python3 etc/ci/taskcluster/decision-task.py diff --git a/.travis.yml b/.travis.yml index 659e2ad4b5ed..e11433ae7771 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,6 @@ matrix: fast_finish: true include: - sudo: false - before_install: - - curl https://sh.rustup.rs -sSf | sh -s -- --default-toolchain none -y - - source ~/.profile script: - ./mach test-tidy --no-progress --all - ./mach test-tidy --no-progress --self-test @@ -20,7 +17,7 @@ matrix: - sudo add-apt-repository 'deb http://apt.llvm.org/precise/ llvm-toolchain-precise-3.9 main' -y - sudo apt-get update -q - sudo apt-get install clang-3.9 llvm-3.9 llvm-3.9-runtime -y - - curl -L https://servo-deps.s3.amazonaws.com/gstreamer/gstreamer-x86_64-linux-gnu.tar.gz | tar xz + - curl -L https://github.com/ferjm/gstreamer-1.14.1-ubuntu-trusty/raw/master/gstreamer.tar.gz | tar xz - sed -i "s;prefix=/root/gstreamer;prefix=$PWD/gstreamer;g" $PWD/gstreamer/lib/x86_64-linux-gnu/pkgconfig/*.pc - export PKG_CONFIG_PATH=$PWD/gstreamer/lib/x86_64-linux-gnu/pkgconfig - export GST_PLUGIN_SYSTEM_PATH=$PWD/gstreamer/lib/x86_64-linux-gnu/gstreamer-1.0 @@ -46,8 +43,6 @@ matrix: before_cache: - ./mach clean-nightlies --keep 2 --force - ./mach clean-cargo-cache --keep 2 --force - - rm -rf $HOME/.cargo/registry - - rm -rf $HOME/.servo/target env: CC=gcc-6 CXX=g++-6 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9d4725878429..bc3240c7d1a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,7 @@ Should you wish to work on an issue, please claim it first by commenting on the GitHub issue that you want to work on it. This is to prevent duplicated efforts from contributors on the same issue. -Head over to [Servo Starters](https://starters.servo.org/) to find +Head over to [Servo Starters](http://servo.github.io/servo-starters/) to find good tasks to start with. If you come across words or jargon that do not make sense, please check [the glossary](docs/glossary.md) first. If there's no matching entry, please make a pull request to add one with the content `TODO` @@ -46,7 +46,7 @@ For specific git instructions, see [GitHub workflow 101](https://github.com/serv ## Conduct -In all Servo-related forums, we follow the [Rust Code of Conduct](https://www.rust-lang.org/conduct.html). For escalation or moderation issues, please contact Jack (jmoffitt@mozilla.com) and Lars (larsberg@mozilla.com) instead of the Rust moderation team. +In all Servo-related forums, we follow the [Rust Code of Conduct](http://www.rust-lang.org/conduct.html). For escalation or moderation issues, please contact Jack (jmoffitt@mozilla.com) and Lars (larsberg@mozilla.com) instead of the Rust moderation team. ## Communication diff --git a/Cargo.lock b/Cargo.lock index 53977e0c6a86..6d839d69c0e1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13,7 +13,7 @@ dependencies = [ [[package]] name = "alloc-no-stdlib" -version = "1.3.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -57,7 +57,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -68,11 +68,6 @@ dependencies = [ "nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "arrayref" -version = "0.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "arrayvec" version = "0.4.6" @@ -102,6 +97,16 @@ dependencies = [ "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "audio-video-metadata" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "mp3-metadata 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mp4parse 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "ogg_metadata 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "azure" version = "0.34.0" @@ -123,7 +128,7 @@ dependencies = [ "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "rustc-demangle 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -137,7 +142,7 @@ dependencies = [ [[package]] name = "base64" -version = "0.9.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -155,7 +160,7 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -178,24 +183,25 @@ dependencies = [ "which 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "bitflags" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "bitflags" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "block" -version = "0.1.6" +name = "bitreader" +version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "block-buffer" -version = "0.3.3" +name = "block" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", - "byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "bluetooth" @@ -219,7 +225,7 @@ dependencies = [ "embedder_traits 0.0.1", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -230,7 +236,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "blurmac" version = "0.1.0" -source = "git+https://github.com/servo/devices#967e13521ac9825a6664f1ed3fb2d2025cac0371" +source = "git+https://github.com/servo/devices#eeb6eaddb79c019bb5c85558b3410b836da57a57" dependencies = [ "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "objc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -238,19 +244,19 @@ dependencies = [ [[package]] name = "blurmock" -version = "0.1.3" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "blurz" -version = "0.3.0" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "dbus 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", + "dbus 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -260,19 +266,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "brotli" -version = "2.5.0" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "alloc-no-stdlib 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", - "brotli-decompressor 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)", + "alloc-no-stdlib 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "brotli-decompressor 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "brotli-decompressor" -version = "1.3.1" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "alloc-no-stdlib 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "alloc-no-stdlib 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -285,11 +291,6 @@ name = "byte-slice-cast" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "byte-tools" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "byteorder" version = "1.2.1" @@ -297,7 +298,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "bytes" -version = "0.4.9" +version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -329,15 +330,14 @@ dependencies = [ "azure 0.34.0 (git+https://github.com/servo/rust-azure)", "canvas_traits 0.0.1", "compositing 0.0.1", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "offscreen_gl_context 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)", - "pixels 0.0.1", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", "servo_config 0.0.1", "webrender 0.57.2 (git+https://github.com/servo/webrender)", @@ -348,15 +348,15 @@ dependencies = [ name = "canvas_traits" version = "0.0.1" dependencies = [ - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "offscreen_gl_context 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", "servo_config 0.0.1", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", @@ -399,7 +399,7 @@ name = "cgl" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -454,7 +454,7 @@ name = "clipboard-win" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -509,10 +509,9 @@ dependencies = [ "embedder_traits 0.0.1", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx_traits 0.0.1", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", @@ -547,9 +546,8 @@ dependencies = [ "gaol 0.0.1 (git+https://github.com/servo/gaol)", "gfx 0.0.1", "gfx_traits 0.0.1", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "layout_traits 0.0.1", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "metrics 0.0.1", @@ -558,7 +556,7 @@ dependencies = [ "net_traits 0.0.1", "profile_traits 0.0.1", "script_traits 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", "servo_config 0.0.1", "servo_rand 0.0.1", @@ -571,7 +569,7 @@ dependencies = [ [[package]] name = "cookie" -version = "0.11.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", @@ -579,16 +577,16 @@ dependencies = [ [[package]] name = "core-foundation" -version = "0.6.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "core-foundation-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation-sys 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "core-foundation-sys" -version = "0.6.2" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -597,29 +595,18 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "core-graphics" -version = "0.17.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "core-text" -version = "13.1.0" +version = "11.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -653,15 +640,6 @@ dependencies = [ "crossbeam-utils 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "crossbeam-deque" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-epoch 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "crossbeam-epoch" version = "0.3.1" @@ -676,19 +654,6 @@ dependencies = [ "scopeguard 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "crossbeam-epoch" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "scopeguard 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "crossbeam-epoch" version = "0.6.0" @@ -717,18 +682,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cssparser" -version = "0.25.0" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cssparser-macros 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "dtoa-short 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "procedural-masquerade 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", "syn 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -738,7 +703,7 @@ name = "cssparser-macros" version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "procedural-masquerade 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -777,11 +742,11 @@ dependencies = [ [[package]] name = "dbus" -version = "0.6.3" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "libdbus-sys 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "libdbus-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -790,7 +755,7 @@ version = "0.0.1" dependencies = [ "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", - "ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "ws 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -820,12 +785,12 @@ dependencies = [ [[package]] name = "device" version = "0.0.1" -source = "git+https://github.com/servo/devices#967e13521ac9825a6664f1ed3fb2d2025cac0371" +source = "git+https://github.com/servo/devices#eeb6eaddb79c019bb5c85558b3410b836da57a57" dependencies = [ "blurdroid 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", "blurmac 0.1.0 (git+https://github.com/servo/devices)", - "blurmock 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "blurz 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "blurmock 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "blurz 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -833,15 +798,12 @@ name = "devtools" version = "0.0.1" dependencies = [ "devtools_traits 0.0.1", - "headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", @@ -852,31 +814,24 @@ name = "devtools_traits" version = "0.0.1" dependencies = [ "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "msg 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_url 0.0.1", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "digest" -version = "0.7.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "dirs" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -923,14 +878,16 @@ dependencies = [ [[package]] name = "dwrote" -version = "0.6.0" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ + "gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -943,11 +900,10 @@ name = "embedder_traits" version = "0.0.1" dependencies = [ "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", "servo_url 0.0.1", "style_traits 0.0.1", @@ -1048,7 +1004,7 @@ version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1060,11 +1016,6 @@ dependencies = [ "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "fake-simd" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "fallible" version = "0.0.1" @@ -1148,20 +1099,6 @@ dependencies = [ "new_debug_unreachable 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "futures" -version = "0.1.23" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "futures-cpupool" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "fxhash" version = "0.2.1" @@ -1189,14 +1126,6 @@ dependencies = [ "winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "generic-array" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "getopts" version = "0.2.17" @@ -1209,10 +1138,10 @@ dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-text 13.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "dwrote 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-text 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "dwrote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", "fontsan 0.4.0 (git+https://github.com/servo/fontsan)", @@ -1228,7 +1157,7 @@ dependencies = [ "ordered-float 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "packed_simd 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "range 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo-fontconfig 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_allocator 0.0.1", "servo_arc 0.1.1", @@ -1253,7 +1182,7 @@ dependencies = [ "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "range 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1277,7 +1206,7 @@ dependencies = [ [[package]] name = "gleam" -version = "0.6.5" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1317,7 +1246,7 @@ dependencies = [ "android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "cgl 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "cocoa 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -1326,7 +1255,7 @@ dependencies = [ "osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "shared_library 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "wayland-client 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "winit 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", "x11-dl 2.18.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1525,23 +1454,6 @@ name = "gvr-sys" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "h2" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "indexmap 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "string 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "half" version = "1.0.0" @@ -1565,41 +1477,6 @@ dependencies = [ "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "headers-core" -version = "0.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "headers-derive" -version = "0.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "headers-ext" -version = "0.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-derive 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", - "sha-1 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "heartbeats-simple" version = "0.4.0" @@ -1619,11 +1496,6 @@ dependencies = [ "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "hex" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "histogram" version = "0.6.8" @@ -1642,19 +1514,9 @@ dependencies = [ "syn 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "http" -version = "0.1.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "httparse" -version = "1.3.2" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -1667,57 +1529,41 @@ dependencies = [ [[package]] name = "hyper" -version = "0.12.12" +version = "0.10.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "h2 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "httparse 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "httparse 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-tcp 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)", + "traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "hyper-openssl" -version = "0.6.1" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "linked_hash_set 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl 0.10.11 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.35 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-openssl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.9.24 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "hyper_serde" -version = "0.9.0" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1764,11 +1610,6 @@ dependencies = [ "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "indexmap" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "inflate" version = "0.4.3" @@ -1779,16 +1620,11 @@ dependencies = [ [[package]] name = "influent" -version = "0.5.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -1797,8 +1633,8 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cgl 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "leaky-cow 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1822,9 +1658,9 @@ dependencies = [ "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.15 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -1897,17 +1733,13 @@ dependencies = [ ] [[package]] -name = "keyboard-types" -version = "0.4.2-servo" +name = "khronos_api" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] -name = "khronos_api" -version = "2.1.0" +name = "language-tags" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -1938,7 +1770,7 @@ dependencies = [ "script_layout_interface 0.0.1", "script_traits 0.0.1", "selectors 0.20.0", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "servo_atoms 0.0.1", @@ -2025,7 +1857,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "lazycell" -version = "1.0.0" +version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -2048,7 +1880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "libdbus-sys" -version = "0.1.4" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2060,17 +1892,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cc 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "libmlservo" -version = "0.0.1" -dependencies = [ - "libservo 0.0.1", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "servo-egl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2092,7 +1914,7 @@ dependencies = [ "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gaol 0.0.1 (git+https://github.com/servo/gaol)", "gfx 0.0.1", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "layout_thread 0.0.1", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2130,7 +1952,7 @@ dependencies = [ "libservo 0.0.1", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2144,19 +1966,6 @@ dependencies = [ "vcpkg 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "linked-hash-map" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "linked_hash_set" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "linked-hash-map 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "lock_api" version = "0.1.3" @@ -2205,15 +2014,14 @@ name = "malloc_size_of" version = "0.0.1" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "hashglobe 0.1.0", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", - "mozjs 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", + "mozjs 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.20.0", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "servo_channel 0.0.1", @@ -2222,7 +2030,7 @@ dependencies = [ "string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "thin-slice 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", "xml5ever 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2250,10 +2058,10 @@ name = "markup5ever" version = "0.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache_codegen 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2279,7 +2087,7 @@ version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2321,21 +2129,21 @@ dependencies = [ [[package]] name = "mime" -version = "0.3.12" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "unicase 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "mime_guess" -version = "2.0.0-alpha.6" +version = "1.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", - "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2369,14 +2177,14 @@ dependencies = [ [[package]] name = "mio" -version = "0.6.16" +version = "0.6.15" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "lazycell 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "lazycell 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2385,27 +2193,6 @@ dependencies = [ "winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "mio-extras" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lazycell 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "mio-uds" -version = "0.6.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "miow" version = "0.2.1" @@ -2433,20 +2220,20 @@ dependencies = [ [[package]] name = "mozjs" -version = "0.9.3" +version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cc 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mozjs_sys 0.61.2 (registry+https://github.com/rust-lang/crates.io-index)", + "mozjs_sys 0.61.0 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "mozjs_sys" -version = "0.61.2" +version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "bindgen 0.39.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2455,22 +2242,39 @@ dependencies = [ "libz-sys 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "mp3-metadata" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "mp4parse" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitreader 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", + "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "msdos_time" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "msg" version = "0.0.1" dependencies = [ + "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "size_of_test 0.0.1", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", ] @@ -2484,20 +2288,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "net" version = "0.0.1" dependencies = [ - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "brotli 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "brotli 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "devtools_traits 0.0.1", "embedder_traits 0.0.1", "flate2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper-openssl 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper-openssl 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "immeta 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2505,30 +2304,26 @@ dependencies = [ "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", - "mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "mime_guess 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", "net_traits 0.0.1", - "openssl 0.10.11 (registry+https://github.com/rust-lang/crates.io-index)", - "pixels 0.0.1", + "openssl 0.9.24 (registry+https://github.com/rust-lang/crates.io-index)", "profile_traits 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "servo_allocator 0.0.1", "servo_arc 0.1.1", "servo_channel 0.0.1", "servo_config 0.0.1", "servo_url 0.0.1", - "std_test_override 0.0.1", "threadpool 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-openssl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", - "ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "ws 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2538,36 +2333,30 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "net_traits" version = "0.0.1" dependencies = [ - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "embedder_traits 0.0.1", - "headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "pixels 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "servo_config 0.0.1", "servo_url 0.0.1", - "std_test_override 0.0.1", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", ] @@ -2693,36 +2482,52 @@ version = "0.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cgl 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "objc 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "x11 2.17.3 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "ogg" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "ogg_metadata" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "ogg 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "openssl" -version = "0.10.11" +version = "0.9.24" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", + "bitflags 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)", "foreign-types 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.35 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl-sys 0.9.27 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "openssl-sys" -version = "0.9.35" +version = "0.9.27" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cc 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2747,8 +2552,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "osmesa-src" -version = "0.1.0" -source = "git+https://github.com/servo/osmesa-src#97f4613fd80eee153ab134dfe349777bc5a27bab" +version = "18.1.0-devel" +source = "git+https://github.com/servo/osmesa-src#25825d4ca357cdaf540f20fafc545f5aff1aa355" [[package]] name = "osmesa-sys" @@ -2796,7 +2601,7 @@ dependencies = [ "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2820,44 +2625,37 @@ dependencies = [ [[package]] name = "phf" -version = "0.7.23" +version = "0.7.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf_codegen" -version = "0.7.23" +version = "0.7.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf_generator 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_generator 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf_generator" -version = "0.7.23" +version = "0.7.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "phf_shared" -version = "0.7.23" +version = "0.7.21" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "siphasher 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", - "unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "pixels" -version = "0.0.1" -dependencies = [ - "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", + "unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2867,7 +2665,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "plane-split" -version = "0.13.3" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", @@ -2923,19 +2721,18 @@ name = "profile" version = "0.0.1" dependencies = [ "heartbeats-simple 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "influent 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", + "influent 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "jemalloc-sys 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "profile_traits 0.0.1", "regex 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", - "servo_allocator 0.0.1", "servo_config 0.0.1", "task_info 0.0.1", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -2945,6 +2742,7 @@ dependencies = [ "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "profile 0.0.1", "profile_traits 0.0.1", + "servo_allocator 0.0.1", "servo_config 0.0.1", ] @@ -2957,7 +2755,7 @@ dependencies = [ "energymon 0.3.0 (git+https://github.com/energymon/energymon-rust.git)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", "servo_config 0.0.1", "signpost 0.1.0 (git+https://github.com/pcwalton/signpost.git)", @@ -3002,7 +2800,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3014,7 +2812,7 @@ dependencies = [ "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "rand_core 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3029,7 +2827,7 @@ dependencies = [ "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3038,18 +2836,19 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "either 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rayon-core 1.4.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rayon-core 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "rayon-core" -version = "1.4.1" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "crossbeam-deque 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3100,7 +2899,7 @@ name = "remove_dir_all" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3108,7 +2907,7 @@ name = "ron" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3130,8 +2929,8 @@ version = "0.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "android_injected_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3140,6 +2939,19 @@ name = "rustc-demangle" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" +[[package]] +name = "rustc-serialize" +version = "0.3.24" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rustc_version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)", +] + [[package]] name = "safemem" version = "0.2.0" @@ -3150,7 +2962,7 @@ name = "same-file" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3168,8 +2980,9 @@ name = "script" version = "0.0.1" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", + "audio-video-metadata 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "bluetooth_traits 0.0.1", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3177,8 +2990,8 @@ dependencies = [ "caseless 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "chrono 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "cmake 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "deny_public_fields 0.0.1", "devtools_traits 0.0.1", "dom_struct 0.0.1", @@ -3188,39 +3001,34 @@ dependencies = [ "enum-iterator 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "half 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "html5ever 0.22.3 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "itertools 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", "jstraceable_derive 0.0.1", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "metrics 0.0.1", - "mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)", - "mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)", + "mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", + "mime_guess 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)", "mitochondria 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "mozangle 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", - "mozjs 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)", + "mozjs 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", "net_traits 0.0.1", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "offscreen_gl_context 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "pixels 0.0.1", + "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "profile_traits 0.0.1", "ref_filter_map 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "ref_slice 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3229,7 +3037,7 @@ dependencies = [ "script_plugins 0.0.1", "script_traits 0.0.1", "selectors 0.20.0", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "servo-media 0.1.0 (git+https://github.com/servo/media)", @@ -3248,7 +3056,7 @@ dependencies = [ "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", "tinyfiledialogs 3.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-segmentation 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "utf-8 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", @@ -3263,7 +3071,7 @@ dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "canvas_traits 0.0.1", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx_traits 0.0.1", "html5ever 0.22.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3304,7 +3112,7 @@ name = "script_tests" version = "0.0.1" dependencies = [ "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", + "msg 0.0.1", "script 0.0.1", "servo_url 0.0.1", ] @@ -3315,29 +3123,28 @@ version = "0.0.1" dependencies = [ "bluetooth_traits 0.0.1", "canvas_traits 0.0.1", - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "devtools_traits 0.0.1", "embedder_traits 0.0.1", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gfx_traits 0.0.1", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "msg 0.0.1", "net_traits 0.0.1", "profile_traits 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_atoms 0.0.1", "servo_channel 0.0.1", "servo_url 0.0.1", "style_traits 0.0.1", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", "webvr_traits 0.0.1", ] @@ -3347,24 +3154,29 @@ name = "selectors" version = "0.20.0" dependencies = [ "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", "thin-slice 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", ] +[[package]] +name = "semver" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "serde" -version = "1.0.80" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3372,17 +3184,17 @@ name = "serde_bytes" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "serde_derive" -version = "1.0.80" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "proc-macro2 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "syn 0.15.6 (registry+https://github.com/rust-lang/crates.io-index)", + "syn 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3393,7 +3205,7 @@ dependencies = [ "dtoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "itoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3402,17 +3214,15 @@ version = "0.0.1" dependencies = [ "backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cc 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)", "crossbeam-channel 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "glutin 0.18.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "libservo 0.0.1", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "osmesa-src 0.1.0 (git+https://github.com/servo/osmesa-src)", + "osmesa-src 18.1.0-devel (git+https://github.com/servo/osmesa-src)", "osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "sig 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", "tinyfiledialogs 3.3.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3462,7 +3272,7 @@ dependencies = [ [[package]] name = "servo-media" version = "0.1.0" -source = "git+https://github.com/servo/media#3b347d7b0431c58611e2bd7b22d34062b64cda26" +source = "git+https://github.com/servo/media#e700a0834c3f38d49890d846591fd699e7405a48" dependencies = [ "servo-media-audio 0.1.0 (git+https://github.com/servo/media)", "servo-media-gstreamer 0.1.0 (git+https://github.com/servo/media)", @@ -3472,16 +3282,15 @@ dependencies = [ [[package]] name = "servo-media-audio" version = "0.1.0" -source = "git+https://github.com/servo/media#3b347d7b0431c58611e2bd7b22d34062b64cda26" +source = "git+https://github.com/servo/media#e700a0834c3f38d49890d846591fd699e7405a48" dependencies = [ "boxfnonce 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "byte-slice-cast 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", "petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_media_derive 0.1.0 (git+https://github.com/servo/media)", "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3489,7 +3298,7 @@ dependencies = [ [[package]] name = "servo-media-gstreamer" version = "0.1.0" -source = "git+https://github.com/servo/media#3b347d7b0431c58611e2bd7b22d34062b64cda26" +source = "git+https://github.com/servo/media#e700a0834c3f38d49890d846591fd699e7405a48" dependencies = [ "byte-slice-cast 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "glib 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3507,11 +3316,11 @@ dependencies = [ [[package]] name = "servo-media-player" version = "0.1.0" -source = "git+https://github.com/servo/media#3b347d7b0431c58611e2bd7b22d34062b64cda26" +source = "git+https://github.com/servo/media#e700a0834c3f38d49890d846591fd699e7405a48" dependencies = [ "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3523,7 +3332,7 @@ dependencies = [ "cmake 0.1.29 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "expat-sys 2.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "glutin 0.18.0 (registry+https://github.com/rust-lang/crates.io-index)", "glx 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "io-surface 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3547,7 +3356,7 @@ name = "servo_arc" version = "0.1.1" dependencies = [ "nodrop 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3565,7 +3374,7 @@ version = "0.0.1" dependencies = [ "crossbeam-channel 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3580,12 +3389,11 @@ dependencies = [ "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_geometry 0.0.1", "servo_url 0.0.1", - "std_test_override 0.0.1", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -3603,7 +3411,7 @@ dependencies = [ [[package]] name = "servo_media_derive" version = "0.1.0" -source = "git+https://github.com/servo/media#3b347d7b0431c58611e2bd7b22d34062b64cda26" +source = "git+https://github.com/servo/media#e700a0834c3f38d49890d846591fd699e7405a48" dependencies = [ "quote 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "syn 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3633,27 +3441,16 @@ version = "0.0.1" dependencies = [ "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_rand 0.0.1", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "url_serde 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "sha-1" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "block-buffer 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", - "byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)", - "fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "sha1" -version = "0.6.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -3684,6 +3481,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" name = "size_of_test" version = "0.0.1" +[[package]] +name = "slab" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + [[package]] name = "slab" version = "0.4.1" @@ -3724,18 +3526,6 @@ name = "stable_deref_trait" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "std_test_override" -version = "0.0.1" -dependencies = [ - "embedder_traits 0.0.1", -] - -[[package]] -name = "string" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "string_cache" version = "0.7.3" @@ -3743,9 +3533,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "new_debug_unreachable 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache_codegen 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -3755,8 +3545,8 @@ name = "string_cache_codegen" version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "phf_generator 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", - "phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_generator 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", + "phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)", "proc-macro2 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "quote 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", "string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3783,7 +3573,7 @@ dependencies = [ "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "encoding_rs 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "fallible 0.0.1", @@ -3809,7 +3599,7 @@ dependencies = [ "rayon 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", "selectors 0.20.0", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "servo_atoms 0.0.1", "servo_channel 0.0.1", @@ -3846,7 +3636,7 @@ version = "0.0.1" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "html5ever 0.22.3 (registry+https://github.com/rust-lang/crates.io-index)", "parking_lot 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", @@ -3858,7 +3648,6 @@ dependencies = [ "servo_config 0.0.1", "servo_url 0.0.1", "size_of_test 0.0.1", - "std_test_override 0.0.1", "style 0.0.1", "style_traits 0.0.1", ] @@ -3869,12 +3658,12 @@ version = "0.0.1" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", - "cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "malloc_size_of 0.0.1", "malloc_size_of_derive 0.0.1", "selectors 0.20.0", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "servo_arc 0.1.1", "servo_atoms 0.0.1", "servo_url 0.0.1", @@ -3906,16 +3695,6 @@ dependencies = [ "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "syn" -version = "0.15.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "proc-macro2 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", - "quote 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", - "unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "synstructure" version = "0.8.1" @@ -3943,7 +3722,7 @@ dependencies = [ "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "redox_syscall 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)", "remove_dir_all 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4027,170 +3806,17 @@ dependencies = [ ] [[package]] -name = "tokio" -version = "0.1.8" +name = "toml" +version = "0.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-codec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-current-thread 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-fs 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-tcp 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-threadpool 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-timer 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-udp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-uds 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] -name = "tokio-codec" +name = "traitobject" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-current-thread" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-executor" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-fs" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-threadpool 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-io" -version = "0.1.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-openssl" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl 0.10.11 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-reactor" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-tcp" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-threadpool" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-deque 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)", - "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "num_cpus 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-timer" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-udp" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-codec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "tokio-uds" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "mio-uds 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "toml" -version = "0.4.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", -] [[package]] name = "truetype" @@ -4198,13 +3824,8 @@ version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] -name = "try-lock" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "typenum" -version = "1.10.0" +name = "typeable" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] @@ -4227,18 +3848,10 @@ dependencies = [ [[package]] name = "unicase" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "version_check 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "unicase" -version = "2.1.0" +version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "version_check 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4247,8 +3860,8 @@ version = "0.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "matches 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4289,7 +3902,7 @@ dependencies = [ [[package]] name = "url" -version = "1.7.1" +version = "1.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "idna 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4302,8 +3915,8 @@ name = "url_serde" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4335,7 +3948,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4348,11 +3961,6 @@ name = "vec_map" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "version_check" -version = "0.1.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "void" version = "1.0.2" @@ -4364,17 +3972,7 @@ version = "2.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "same-file 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "want" -version = "0.0.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4429,103 +4027,95 @@ dependencies = [ [[package]] name = "webdriver" -version = "0.37.0" +version = "0.35.1" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)", - "http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "regex 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", - "tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-segmentation 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "webdriver_server" version = "0.0.1" dependencies = [ - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", - "hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)", + "hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", "net_traits 0.0.1", "regex 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", + "rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)", "script_traits 0.0.1", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "servo_channel 0.0.1", "servo_config 0.0.1", "servo_url 0.0.1", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "webdriver 0.37.0 (registry+https://github.com/rust-lang/crates.io-index)", + "webdriver 0.35.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "webrender" version = "0.57.2" -source = "git+https://github.com/servo/webrender#790b76f1547453615262c3037e1fb04bda22fbc8" +source = "git+https://github.com/servo/webrender#38f3b57cd9bf2c6fb736d14832fee87eb576e322" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", - "base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", + "base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "cfg-if 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-text 13.1.0 (registry+https://github.com/rust-lang/crates.io-index)", - "dwrote 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-text 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)", + "dwrote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "freetype 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", + "gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", "num-traits 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)", - "plane-split 0.13.3 (registry+https://github.com/rust-lang/crates.io-index)", + "plane-split 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)", "rayon 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "ron 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)", "thread_profiler 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", "webrender_api 0.57.2 (git+https://github.com/servo/webrender)", - "ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)", + "ws 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "webrender_api" version = "0.57.2" -source = "git+https://github.com/servo/webrender#790b76f1547453615262c3037e1fb04bda22fbc8" +source = "git+https://github.com/servo/webrender#38f3b57cd9bf2c6fb736d14832fee87eb576e322" dependencies = [ "app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)", "bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", - "core-graphics 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)", - "dwrote 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", + "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", + "dwrote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", "euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)", - "serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", "time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4552,7 +4142,7 @@ dependencies = [ "ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "msg 0.0.1", "rust-webvr-api 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)", - "serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)", + "serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4570,7 +4160,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" -version = "0.3.6" +version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4597,7 +4187,7 @@ name = "wincolor" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4607,7 +4197,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)", "cocoa 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)", - "core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)", + "core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", "core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)", "image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)", "lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -4618,7 +4208,7 @@ dependencies = [ "percent-encoding 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", "smithay-client-toolkit 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)", "wayland-client 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)", "x11-dl 2.18.3 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -4632,20 +4222,19 @@ dependencies = [ [[package]] name = "ws" -version = "0.7.9" +version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)", - "httparse 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)", - "log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)", - "mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)", - "mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl 0.10.11 (registry+https://github.com/rust-lang/crates.io-index)", - "rand 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)", - "sha1 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)", - "slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", - "url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)", + "bytes 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)", + "httparse 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", + "log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)", + "mio 0.6.15 (registry+https://github.com/rust-lang/crates.io-index)", + "openssl 0.9.24 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)", + "sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", + "slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)", + "url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] @@ -4732,7 +4321,7 @@ dependencies = [ [metadata] "checksum adler32 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7e522997b529f05601e05166c07ed17789691f562762c7f3b987263d2dedee5c" "checksum aho-corasick 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "f0ba20154ea1f47ce2793322f049c5646cc6d0fa9759d5f333f286e507bf8080" -"checksum alloc-no-stdlib 1.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "71877e174a5d78c969228d628c4f7f3b545d13452bd3d9393fa07aacfb7c6894" +"checksum alloc-no-stdlib 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b21f6ad9c9957eb5d70c3dee16d31c092b3cab339628f821766b05e6833d72b8" "checksum android_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "000444226fcff248f2bc4c7625be32c63caccfecc2723a2b9f78a7487a49c407" "checksum android_injected_glue 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "80b9e34fcbf29c0563547cb2ecce9b49504597cad6166769b1e4efb45c6c2951" "checksum android_log-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b8052e2d8aabbb8d556d6abbcce2a22b9590996c5f849b9c7ce4544a2e3b984e" @@ -4741,33 +4330,33 @@ dependencies = [ "checksum antidote 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "34fde25430d87a9388dadbe6e34d7f72a462c8b43ac8d309b42b0a8505d7e2a5" "checksum app_units 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9dadc668390b373e73e4abbfc1f07238b09a25858f2f39c06cebc6d8e141d774" "checksum array-init 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "c3cc8456d0ae81a8c76f59e384683a601548c38949a4bfcb65dd31ded5c75ff3" -"checksum arrayref 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "0d382e583f07208808f6b1249e60848879ba3543f57c32277bf52d69c2f0f0ee" "checksum arrayvec 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2f0ef4a9820019a0c91d918918c93dc71d469f581a49b47ddc1d285d4270bbe2" "checksum ascii 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3ae7d751998c189c1d4468cf0a39bb2eae052a9c58d50ebb3b9591ee3813ad50" "checksum atomic_refcell 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fb2dcb6e6d35f20276943cc04bb98e538b348d525a04ac79c10021561d202f21" "checksum atty 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "21e50800ec991574876040fff8ee46b136a53e985286fbe6a3bdfe6421b78860" +"checksum audio-video-metadata 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "3c23600291b35b9cd381f5cfca636f5d7d75e7d7192eddf867de84a6732cad5c" "checksum azure 0.34.0 (git+https://github.com/servo/rust-azure)" = "" "checksum backtrace 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "89a47830402e9981c5c41223151efcced65a0510c13097c769cede7efb34782a" "checksum backtrace-sys 0.1.24 (registry+https://github.com/rust-lang/crates.io-index)" = "c66d56ac8dabd07f6aacdaf633f4b8262f5b3601a810a0dcddffd5c22c69daa0" -"checksum base64 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "85415d2594767338a74a30c1d370b2f3262ec1b4ed2d7bba5b3faf4de40467d9" +"checksum base64 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "96434f987501f0ed4eb336a411e0631ecd1afa11574fe148587adc4ff96143c9" "checksum binary-space-partition 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88ceb0d16c4fd0e42876e298d7d3ce3780dd9ebdcbe4199816a32c77e08597ff" "checksum bincode 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bda13183df33055cbb84b847becce220d392df502ebe7a4a78d7021771ed94d0" "checksum bindgen 0.39.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eac4ed5f2de9efc3c87cb722468fa49d0763e98f999d539bfc5e452c13d85c91" +"checksum bitflags 0.9.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4efd02e230a02e18f92fc2735f44597385ed02ad8f831e7c1c1156ee5e1ab3a5" "checksum bitflags 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "d0c54bb8f454c567f21197eefcdbf5679d0bd99f2ddbe52e84c77061952e6789" +"checksum bitreader 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "80b13e2ab064ff3aa0bdbf1eff533f9822dc37899821f5f98c67f263eab51707" "checksum block 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" -"checksum block-buffer 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a076c298b9ecdb530ed9d967e74a6027d6a7478924520acddcddc24c1c8ab3ab" "checksum blurdroid 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "19b23557dd27704797128f9db2816416bef20dad62d4a9768714eeb65f07d296" "checksum blurmac 0.1.0 (git+https://github.com/servo/devices)" = "" -"checksum blurmock 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9c150fd617830fd121919bbd500a784507e8af1bae744efcf587591c65c375d4" -"checksum blurz 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f6dae8337ff67fe8ead29a28a0115605753e6a5205d4b6017e9f42f198c3c50a" +"checksum blurmock 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "68dd72da3a3bb40f3d3bdd366c4cf8e2b1d208c366304f382c80cef8126ca8da" +"checksum blurz 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e73bda0f4c71c63a047351070097f3f507e6718e86b9ee525173371ef7b94b73" "checksum boxfnonce 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cbec60c560f322d8e3cd403f91d8908cfd965fff53ba97154bd1b9d90149d98e" -"checksum brotli 2.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8c6236055e28bc092d6d370f3219e6939d8ba8352b397e290391bb8af0d94f25" -"checksum brotli-decompressor 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "471bf19486c9aaf5b817ed04c49ccc8acd8d28c70d5114e710e8b9f530df89cd" +"checksum brotli 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "fe87b40996b84fdc56e57c165d93079f4b50cb806598118e692ddfaa3d3c57c0" +"checksum brotli-decompressor 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "313f4b6cc0b365d6b88eda5aa40175ee34ac6efa9a79e0b3b8202eca90247ba8" "checksum build_const 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "39092a32794787acd8525ee150305ff051b0aa6cc2abaf193924f5ab05425f39" "checksum byte-slice-cast 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "28346c117b50270785fbc123bd6e4ecad20d0c6d5f43d081dc80a3abcc62be64" -"checksum byte-tools 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "560c32574a12a89ecd91f5e742165893f86e3ab98d21f8ea548658eb9eef5f40" "checksum byteorder 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "652805b7e73fada9d85e9a6682a4abd490cb52d96aeecc12e33a0de34dfd0d23" -"checksum bytes 0.4.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e178b8e0e239e844b083d5a0d4a156b2654e67f9f80144d48398fcd736a24fb8" +"checksum bytes 0.4.6 (registry+https://github.com/rust-lang/crates.io-index)" = "1b7db437d718977f6dc9b2e3fd6fc343c02ac6b899b73fdd2179163447bd9ce9" "checksum bzip2 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "42b7c3cbf0fa9c1b82308d57191728ca0256cb821220f4e2fd410a72ade26e3b" "checksum bzip2-sys 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2c5162604199bbb17690ede847eaa6120a3f33d5ab4dcc8e7c25b16d849ae79b" "checksum caseless 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "808dab3318747be122cb31d36de18d4d1c81277a76f8332a02b81a3d73463d7f" @@ -4786,36 +4375,32 @@ dependencies = [ "checksum cocoa 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f5cd1afb83b2de9c41e5dfedb2bcccb779d433b958404876009ae4b01746ff23" "checksum color_quant 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a475fc4af42d83d28adf72968d9bcfaf035a1a9381642d8e85d8a04957767b0d" "checksum combine 3.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "54cedd8056314afe0d844a37a207007edf8a45f2cc452fd77629cd63c221740e" -"checksum cookie 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1465f8134efa296b4c19db34d909637cb2bf0f7aaf21299e23e18fa29ac557cf" -"checksum core-foundation 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "58667b9a618a37ea8c4c4cb5298703e5dfadcd3698c79f54fc43e6a2e94733ea" -"checksum core-foundation-sys 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e7ca8a5221364ef15ce201e8ed2f609fc312682a8f4e0e3d4aa5879764e0fa3b" +"checksum cookie 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "746858cae4eae40fff37e1998320068df317bc247dc91a67c6cfa053afdc2abb" +"checksum core-foundation 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c7caa6cb9e76ddddbea09a03266d6b3bc98cd41e9fb9b017c473e7cca593ec25" +"checksum core-foundation-sys 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b2a53cce0ddcf7e7e1f998738d757d5a3bf08bf799a180e50ebe50d298f52f5a" "checksum core-graphics 0.16.0 (registry+https://github.com/rust-lang/crates.io-index)" = "92801c908ea6301ae619ed842a72e01098085fc321b9c2f3f833dad555bba055" -"checksum core-graphics 0.17.2 (registry+https://github.com/rust-lang/crates.io-index)" = "46a1b26242df9c08350ffede6684753773eab42289745f618fc42c2f41486ffa" -"checksum core-text 13.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a6705907bc253cee90b8551017836ce50904be305c99fec5ea74a8d72d799e58" +"checksum core-text 11.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "157ff38a92496dc676ce36d9124554e9ac66f1c1039f952690ac64f71cfa5968" "checksum crc 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d663548de7f5cca343f1e0a48d14dcfb0e9eb4e079ec58883b7251539fa10aeb" "checksum crossbeam-channel 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a5716fadb87a5633db34c5e83ee6e036e6edc229f8a6bfb7c7c84ed340ba95df" "checksum crossbeam-deque 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f739f8c5363aca78cfb059edf753d8f0d36908c348f3d8d1503f03d8b75d9cf3" -"checksum crossbeam-deque 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "3486aefc4c0487b9cb52372c97df0a48b8c249514af1ee99703bf70d2f2ceda1" "checksum crossbeam-epoch 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "927121f5407de9956180ff5e936fe3cf4324279280001cd56b669d28ee7e9150" -"checksum crossbeam-epoch 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "30fecfcac6abfef8771151f8be4abc9e4edc112c2bcb233314cafde2680536e9" "checksum crossbeam-epoch 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c90f1474584f38e270b5b613e898c8c328aa4f3dea85e0a27ac2e642f009416" "checksum crossbeam-utils 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "2760899e32a1d58d5abb31129f8fae5de75220bc2176e77ff7c627ae45c918d9" "checksum crossbeam-utils 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "677d453a17e8bd2b913fa38e8b9cf04bcdbb5be790aa294f2389661d72036015" -"checksum cssparser 0.25.0 (registry+https://github.com/rust-lang/crates.io-index)" = "730363a45c4e248d4f21d3e5c1156d1a9cdec0855056c0d9539e814bc59865c3" +"checksum cssparser 0.24.0 (registry+https://github.com/rust-lang/crates.io-index)" = "495beddc39b1987b8e9f029354eccbd5ef88eb5f1cd24badb764dce338acf2e0" "checksum cssparser-macros 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "f3a5383ae18dbfdeb569ed62019f5bddb2a95cd2d3833313c475a0d014777805" "checksum darling 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2a78af487e4eb8f4421a1770687b328af6bb4494ca93435210678c6eea875c11" "checksum darling_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b315f49c7b6db3708bca6e6913c194581a44ec619b7a39e131d4dd63733a3698" "checksum darling_macro 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eb69a38fdeaeaf3db712e1df170de67ee9dfc24fb88ca3e9d21e703ec25a4d8e" -"checksum dbus 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3d975a175aa2dced1a6cd410b89a1bf23918f301eab2b6f7c5e608291b757639" +"checksum dbus 0.5.4 (registry+https://github.com/rust-lang/crates.io-index)" = "acd824d45fad5ff0e178fcb3c040f13780e73f63a0a6d5cde59e7894f251ab0e" "checksum deflate 0.7.5 (registry+https://github.com/rust-lang/crates.io-index)" = "ebb02aaf4b775afc96684b8402510a338086974e38570a1f65bea8c202eb77a7" "checksum device 0.0.1 (git+https://github.com/servo/devices)" = "" -"checksum digest 0.7.6 (registry+https://github.com/rust-lang/crates.io-index)" = "03b072242a8cbaf9c145665af9d250c59af3b958f83ed6824e13533cf76d5b90" "checksum dirs 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "37a76dd8b997af7107d0bb69d43903cf37153a18266f8b3fdb9911f28efb5444" "checksum dlib 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "77e51249a9d823a4cb79e3eca6dcd756153e8ed0157b6c04775d04bf1b13b76a" "checksum downcast-rs 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "18df8ce4470c189d18aa926022da57544f31e154631eb4cfe796aea97051fe6c" "checksum dtoa 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "80c8b71fd71146990a9742fc06dcbbde19161a267e0ad4e572c35162f4578c90" "checksum dtoa-short 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fe6f727b406462fd57c95fed84d1b0dbfb5f0136fcac005adba9ea0367c05cc8" -"checksum dwrote 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8b5a0af6d47ecf67355dc36e5fc09547050bd8a4b87870e637911ffe4aced32a" +"checksum dwrote 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b26e30aaa6bf31ec830db15fec14ed04f0f2ecfcc486ecfce88c55d3389b237f" "checksum either 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "18785c1ba806c258137c937e44ada9ee7e69a37e3c72077542cd2f069d78562a" "checksum encoding_rs 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "f5215aabf22b83153be3ee44dfe3f940214541b2ce13d419c55e7a115c8c51a9" "checksum energy-monitor 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fe872d0664f1cc60db36349af245d892ee67d3c8f78055df0ebc43271fd4e05c" @@ -4829,7 +4414,6 @@ dependencies = [ "checksum error-chain 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "07e791d3be96241c77c43846b665ef1384606da2cd2a48730abe606a12906e02" "checksum euclid 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)" = "70a2ebdf55fb9d6329046e026329a55ef8fbaae5ea833f56e170beb3125a8a5f" "checksum expat-sys 2.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "658f19728920138342f68408b7cf7644d90d4784353d8ebc32e7e8663dbe45fa" -"checksum fake-simd 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e88a8acf291dafb59c2d96e8f59828f3838bb1a70398823ade51a84de6a6deed" "checksum fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33" "checksum flate2 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "9fac2277e84e5e858483756647a9d0aa8d9a2b7cba517fd84325a0aaa69a0909" "checksum fnv 1.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "6cc484842f1e2884faf56f529f960cc12ad8c71ce96cc7abba0a067c98fee344" @@ -4840,16 +4424,13 @@ dependencies = [ "checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" "checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" "checksum futf 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "7c9c1ce3fa9336301af935ab852c437817d14cd33690446569392e65170aac3b" -"checksum futures 0.1.23 (registry+https://github.com/rust-lang/crates.io-index)" = "884dbe32a6ae4cd7da5c6db9b78114449df9953b8d490c9d7e1b51720b922c62" -"checksum futures-cpupool 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "ab90cde24b3319636588d0c35fe03b1333857621051837ed769faefb4c2162e4" "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum gaol 0.0.1 (git+https://github.com/servo/gaol)" = "" "checksum gdi32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0912515a8ff24ba900422ecda800b52f4016a56251922d397c576bf92c690518" -"checksum generic-array 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ef25c5683767570c2bbd7deba372926a55eaae9982d7726ee2a1050239d45b9d" "checksum getopts 0.2.17 (registry+https://github.com/rust-lang/crates.io-index)" = "b900c08c1939860ce8b54dc6a89e26e00c04c380fd0e09796799bd7f12861e05" "checksum gif 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ff3414b424657317e708489d2857d9575f4403698428b040b609b9d1c1a84a2c" "checksum gl_generator 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a795170cbd85b5a7baa58d6d7525cae6a03e486859860c220f7ebbbdd379d0a" -"checksum gleam 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)" = "962cbec852194e0f5f49ea0ca8407740cb14d760d8d86834b19b1f228cb505dd" +"checksum gleam 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0d41e7ac812597988fdae31c9baec3c6d35cadb8ad9ab88a9bf9c0f119ed66c2" "checksum glib 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "740f7fda8dde5f5e3944dabdb4a73ac6094a8a7fdf0af377468e98ca93733e61" "checksum glib-sys 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3573351e846caed9f11207b275cd67bc07f0c2c94fb628e5d7c92ca056c7882d" "checksum glob 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "8be18de09a56b60ed0edf84bc9df007e30040691af7acd1c41874faac5895bfb" @@ -4869,30 +4450,23 @@ dependencies = [ "checksum gstreamer-video 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0c1f04816d7e183714830da26274f97e7aeff09ae6641058538d21443b4ec07d" "checksum gstreamer-video-sys 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d0e2efb301a0b94fa4af503122faa04247085936dd888fd59fa4e21eab3cbd37" "checksum gvr-sys 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1334b94d8ce67319ddc44663daef53d8c1538629a11562530c981dbd9085b9a" -"checksum h2 0.1.12 (registry+https://github.com/rust-lang/crates.io-index)" = "a27e7ed946e8335bdf9a191bc1b9b14a03ba822d013d2f58437f4fabcbd7fc2c" "checksum half 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "63d68db75012a85555434ee079e7e6337931f87a087ab2988becbadf64673a7f" "checksum harfbuzz-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "87a29ce223fee4727c0c4810a1419a3412f65b29146339fb6a47ee39456c34ea" -"checksum headers-core 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7794c3bca3a5fb812a06d43f715cf857f7b037d52d6d8e054231d439dd839073" -"checksum headers-derive 0.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "93b8509be5e3893b8c9c37805a05aa57e4561cf1f1a2aab30cec4931127f36ca" -"checksum headers-ext 0.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6657fda27978455d69652a0c817d5c73d6d3694d97027924477a1e1c66e33f61" "checksum heartbeats-simple 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9ad003ce233955e9d95f2c69cde84e68302ba9ba4a673d351c9bff93c738aadc" "checksum heartbeats-simple-sys 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "e1a408c0011427cc0e0049f7861c70377819aedfc006e8c901b1c70fd98fb1a4" -"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77" "checksum histogram 0.6.8 (registry+https://github.com/rust-lang/crates.io-index)" = "1bdcec4094c1ca961b685384ea7af76af5718230b3f34657d1a71fd2dcf4cc9d" "checksum html5ever 0.22.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b04478cf718862650a0bf66acaf8f2f8c906fbc703f35c916c1f4211b069a364" -"checksum http 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "24f58e8c2d8e886055c3ead7b28793e1455270b5fb39650984c224bc538ba581" -"checksum httparse 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7b6288d7db100340ca12873fd4d08ad1b8f206a9457798dfb17c018a33fee540" +"checksum httparse 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "a6e7a63e511f9edffbab707141fbb8707d1a3098615fb2adbd5769cdfcc9b17d" "checksum humantime 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0484fda3e7007f2a4a0d9c3a703ca38c71c54c55602ce4660c419fd32e188c9e" -"checksum hyper 0.12.12 (registry+https://github.com/rust-lang/crates.io-index)" = "4aca412c241a2dd53af261efc7adf7736fdebd67dc0d1cc1ffdbcb9407e0e810" -"checksum hyper-openssl 0.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ddca42b55aaf1755b417d286d5eaa1f435cd626b53ffbb53bb9cef4d8819ac86" -"checksum hyper_serde 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "af6cd576f3bf6d7dabc34828c16a08c99e71dca01c87e4a5d754c6ea3995f3d9" +"checksum hyper 0.10.13 (registry+https://github.com/rust-lang/crates.io-index)" = "368cb56b2740ebf4230520e2b90ebb0461e69034d85d1945febd9b3971426db2" +"checksum hyper-openssl 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "85a372eb692590b3fe014c196c30f9f52d4c42f58cd49dd94caeee1593c9cc37" +"checksum hyper_serde 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "0997ad463f64ce6ba02cf5af320622bb9782e4f8355b650a2cc7ccca69a7cc2e" "checksum ident_case 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3c9826188e666f2ed92071d2dadef6edc430b11b158b5b2b3f4babbcc891eaaa" "checksum idna 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "014b298351066f1512874135335d62a789ffe78a9974f94b43ed5621951eaf7d" "checksum image 0.19.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ebdff791af04e30089bde8ad2a632b86af433b40c04db8d70ad4b21487db7a6a" "checksum immeta 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7371aa3c98fad60de2d9b517e2e1ed45593c32b0c77249310fa507749a2a318b" -"checksum indexmap 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "08173ba1e906efb6538785a8844dd496f5d34f0a2d88038e95195172fc667220" "checksum inflate 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "6f53b811ee8e2057ccf9643ca6b4277de90efaf5e61e55fd5254576926bb4245" -"checksum influent 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8f06f65fa332019cbf57b927cd5a5da53cfce506109f38312fd597745a8a48c0" +"checksum influent 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a22b311b83431be3ab9af96ca9ea41554bb4a8551ea871ae44c3ce0c57e55f2c" "checksum io-surface 0.11.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5f9a33981dff54baaff80f4decb487a65d148a3c00facc97820d0f09128f74dd" "checksum iovec 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "dbe6e417e7d0975db6512b90796e8ce223145ac4e33c377e4a42882a0e88bb08" "checksum ipc-channel 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "dd75debad4ffd295c00c6e3634d254df30050b0837a85e5cd039ac424365f24a" @@ -4903,18 +4477,16 @@ dependencies = [ "checksum jni-sys 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" "checksum jpeg-decoder 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "0dfe27a6c0dabd772d0f9b9f8701c4ca12c4d1eebcadf2be1f6f70396f6a1434" "checksum kernel32-sys 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7507624b29483431c0ba2d82aece8ca6cdba9382bff4ddd0f7490560c056098d" -"checksum keyboard-types 0.4.2-servo (registry+https://github.com/rust-lang/crates.io-index)" = "75082c134a78e0fc2232d2f30bf3dfdea1cd28591846b85a73b4b46cd776b482" "checksum khronos_api 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d9ef23fcc4059260c5936f638c9805ebfc87cb172fa6661d130cba7f97d58f55" +"checksum language-tags 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "a91d884b6667cd606bb5a69aa0c99ba811a115fc68915e7056ec08a46e93199a" "checksum lazy_static 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "c8f31047daa365f19be14b47c29df4f7c3b581832407daabe6ae77397619237d" -"checksum lazycell 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d33a48d0365c96081958cc663eef834975cb1e8d8bea3378513fc72bdbf11e50" +"checksum lazycell 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a6f08839bc70ef4a3fe1d566d5350f519c5912ea86be0df1740a7d247c7fc0ef" "checksum leak 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bd100e01f1154f2908dfa7d02219aeab25d0b9c7fa955164192e3245255a0c73" "checksum leaky-cow 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "40a8225d44241fd324a8af2806ba635fc7c8a7e9a7de4d5cf3ef54e71f5926fc" "checksum libc 0.2.42 (registry+https://github.com/rust-lang/crates.io-index)" = "b685088df2b950fccadf07a7187c8ef846a959c142338a48f9dc0b94517eb5f1" -"checksum libdbus-sys 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "99c78106156a964aadc1c59f7798276967be6705243b60f3ab7e131e3841db88" +"checksum libdbus-sys 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8720f9274907052cb50313f91201597868da9d625f8dd125f2aca5bddb7e83a1" "checksum libloading 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3ad660d7cb8c5822cd83d10897b0f1f1526792737a179e73896152f85b88c2" "checksum libz-sys 1.0.18 (registry+https://github.com/rust-lang/crates.io-index)" = "87f737ad6cc6fd6eefe3d9dc5412f1573865bded441300904d2f42269e140f16" -"checksum linked-hash-map 0.5.1 (registry+https://github.com/rust-lang/crates.io-index)" = "70fb39025bc7cdd76305867c4eccf2f2dcf6e9a57f5b21a93e1c2d86cd03ec9e" -"checksum linked_hash_set 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3c7c91c4c7bbeb4f2f7c4e5be11e6a05bd6830bc37249c47ce1ad86ad453ff9c" "checksum lock_api 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "949826a5ccf18c1b3a7c3d57692778d21768b79e46eb9dd07bfc4c2160036c54" "checksum log 0.3.9 (registry+https://github.com/rust-lang/crates.io-index)" = "e19e8d5c34a3e0e2223db8e060f9e8264aeeb5c5fc64a4ee9965c062211c024b" "checksum log 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d4fcce5fa49cc693c312001daf1d13411c4a5283796bac1084299ea3e567113f" @@ -4926,19 +4498,19 @@ dependencies = [ "checksum memchr 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "796fba70e76612589ed2ce7f45282f5af869e0fdd7cc6199fa1aa1f1d591ba9d" "checksum memmap 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e2ffa2c986de11a9df78620c01eeaaf27d94d3ff02bf81bfcca953102dd0c6ff" "checksum memoffset 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0f9dc261e2b62d7a622bf416ea3c5245cdd5d9a7fcc428c0d06804dfce1775b3" -"checksum mime 0.3.12 (registry+https://github.com/rust-lang/crates.io-index)" = "0a907b83e7b9e987032439a387e187119cddafc92d5c2aaeb1d92580a793f630" -"checksum mime_guess 2.0.0-alpha.6 (registry+https://github.com/rust-lang/crates.io-index)" = "30de2e4613efcba1ec63d8133f344076952090c122992a903359be5a4f99c3ed" +"checksum mime 0.2.4 (registry+https://github.com/rust-lang/crates.io-index)" = "9d69889cdc6336ed56b174514ce876c4c3dc564cc23dd872e7bca589bb2a36c8" +"checksum mime_guess 1.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "76da6df85047af8c0edfa53f48eb1073012ce1cc95c8fedc0a374f659a89dd65" "checksum miniz-sys 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "609ce024854aeb19a0ef7567d348aaa5a746b32fb72e336df7fcc16869d7e2b4" "checksum miniz_oxide 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9ba430291c9d6cedae28bcd2d49d1c32fc57d60cd49086646c5dd5673a870eb5" "checksum miniz_oxide_c_api 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "5a5b8234d6103ebfba71e29786da4608540f862de5ce980a1c94f86a40ca0d51" -"checksum mio 0.6.16 (registry+https://github.com/rust-lang/crates.io-index)" = "71646331f2619b1026cc302f87a2b8b648d5c6dd6937846a16cc8ce0f347f432" -"checksum mio-extras 2.0.5 (registry+https://github.com/rust-lang/crates.io-index)" = "46e73a04c2fa6250b8d802134d56d554a9ec2922bf977777c805ea5def61ce40" -"checksum mio-uds 0.6.7 (registry+https://github.com/rust-lang/crates.io-index)" = "966257a94e196b11bb43aca423754d87429960a768de9414f3691d6957abf125" +"checksum mio 0.6.15 (registry+https://github.com/rust-lang/crates.io-index)" = "4fcfcb32d63961fb6f367bfd5d21e4600b92cd310f71f9dca25acae196eb1560" "checksum miow 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8c1f2f3b1cf331de6896aabf6e9d55dca90356cc9960cca7eaaf408a355ae919" "checksum mitochondria 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9de3eca27871df31c33b807f834b94ef7d000956f57aa25c5aed9c5f0aae8f6f" "checksum mozangle 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "45a8a18a41cfab0fde25cc2f43ea89064d211a0fbb33225b8ff93ab20406e0e7" -"checksum mozjs 0.9.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bd0bdded611cb03c8ca638e0b663befe67eb7fbcb1fe2dfd25061656ee4ff365" -"checksum mozjs_sys 0.61.2 (registry+https://github.com/rust-lang/crates.io-index)" = "28276d28cc79226f3a26c790f00c8ce74459d097d3698f17df05ab9f683c1e52" +"checksum mozjs 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b9f85c1120b07d7a2acc9d1d62df1fe16f64162399448fb5307bf2bc3bd066c9" +"checksum mozjs_sys 0.61.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1ff07b0f0a2371dc08d75d55371ca311be67e1fdfa6c146fc8ad154c340f70c9" +"checksum mp3-metadata 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ab5f1d2693586420208d1200ce5a51cd44726f055b635176188137aff42c7de" +"checksum mp4parse 0.10.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7316728464443fe5793a805dde3257864e9690cf46374daff3ce93de1df2f254" "checksum msdos_time 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "aad9dfe950c057b1bfe9c1f2aa51583a8468ef2a5baba2ebbe06d775efeb7729" "checksum muldiv 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "451a9a05d2a32c566c897835e0ea95cf79ed2fdfe957924045a1721a36c9980f" "checksum net2 0.2.33 (registry+https://github.com/rust-lang/crates.io-index)" = "42550d9fb7b6684a6d404d9fa7250c2eb2646df731d1c06afc06dcee9e1bcf88" @@ -4957,11 +4529,13 @@ dependencies = [ "checksum objc-foundation 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "1add1b659e36c9607c7aab864a76c7a4c2760cd0cd2e120f3fb8b952c7e22bf9" "checksum objc_id 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e4730aa1c64d722db45f7ccc4113a3e2c465d018de6db4d3e7dfe031e8c8a297" "checksum offscreen_gl_context 0.21.0 (registry+https://github.com/rust-lang/crates.io-index)" = "95f2e39e3b8c95495cfec835b6fefee3f1e7d63c6f81d99796b4f9926c02db3c" -"checksum openssl 0.10.11 (registry+https://github.com/rust-lang/crates.io-index)" = "6c24d3508b4fb6da175c10baac54c578b33f09c89ae90c6fe9788b3b4768efdc" -"checksum openssl-sys 0.9.35 (registry+https://github.com/rust-lang/crates.io-index)" = "912f301a749394e1025d9dcddef6106ddee9252620e6d0a0e5f8d0681de9b129" +"checksum ogg 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7137bf02687385302f4c0aecd77cfce052b69f5b4ee937be778e125c62f67e30" +"checksum ogg_metadata 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fc665717454399cba557c55ad226148996e9266ee291f8a37a98bb2cded0a490" +"checksum openssl 0.9.24 (registry+https://github.com/rust-lang/crates.io-index)" = "a3605c298474a3aa69de92d21139fb5e2a81688d308262359d85cdd0d12a7985" +"checksum openssl-sys 0.9.27 (registry+https://github.com/rust-lang/crates.io-index)" = "d6fdc5c4a02e69ce65046f1763a0181107038e02176233acb0b3351d7cc588f9" "checksum ordered-float 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e9a3c8db0fca1fdb34404f0b1286db252f23930b9f7a481e376c16c0d5c309d4" "checksum ordermap 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a86ed3f5f244b372d6b1a00b72ef7f8876d0bc6a78a4c9985c53614041512063" -"checksum osmesa-src 0.1.0 (git+https://github.com/servo/osmesa-src)" = "" +"checksum osmesa-src 18.1.0-devel (git+https://github.com/servo/osmesa-src)" = "" "checksum osmesa-sys 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "88cfece6e95d2e717e0872a7f53a8684712ad13822a7979bc760b9c77ec0013b" "checksum ovr-mobile-sys 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a69b517feac6fc640f0679625defa0998bbcb32871a6901e63063c2abf9c4cbe" "checksum owning_ref 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "cdf84f41639e037b484f93433aa3897863b561ed65c6e59c7073d7c561710f37" @@ -4971,12 +4545,12 @@ dependencies = [ "checksum peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" "checksum percent-encoding 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "de154f638187706bde41d9b4738748933d64e6b37bdbffc0b47a97d16a6ae356" "checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f" -"checksum phf 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "cec29da322b242f4c3098852c77a0ca261c9c01b806cae85a5572a1eb94db9a6" -"checksum phf_codegen 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "7d187f00cd98d5afbcd8898f6cf181743a449162aeb329dcd2f3849009e605ad" -"checksum phf_generator 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "03dc191feb9b08b0dc1330d6549b795b9d81aec19efe6b4a45aec8d4caee0c4b" -"checksum phf_shared 0.7.23 (registry+https://github.com/rust-lang/crates.io-index)" = "b539898d22d4273ded07f64a05737649dc69095d92cb87c7097ec68e3f150b93" +"checksum phf 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)" = "cb325642290f28ee14d8c6201159949a872f220c62af6e110a56ea914fbe42fc" +"checksum phf_codegen 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)" = "d62594c0bb54c464f633175d502038177e90309daf2e0158be42ed5f023ce88f" +"checksum phf_generator 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)" = "6b07ffcc532ccc85e3afc45865469bf5d9e4ef5bfcf9622e3cfe80c2d275ec03" +"checksum phf_shared 0.7.21 (registry+https://github.com/rust-lang/crates.io-index)" = "07e24b0ca9643bdecd0632f2b3da6b1b89bbb0030e0b992afc1113b23a7bc2f2" "checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c" -"checksum plane-split 0.13.3 (registry+https://github.com/rust-lang/crates.io-index)" = "9b1d9a84aa3bbc2dafd06856bdb1dc333eb1d442ad8987b9d596c7344b3ed969" +"checksum plane-split 0.12.1 (registry+https://github.com/rust-lang/crates.io-index)" = "ff3a4fc9e31d70eb6828e9a2d7a401a824d9f281686a39a8fc06f08796edb1bb" "checksum png 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f54b9600d584d3b8a739e1662a595fab051329eff43f20e7d8cc22872962145b" "checksum podio 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "780fb4b6698bbf9cf2444ea5d22411cef2953f0824b98f33cf454ec5615645bd" "checksum precomputed-hash 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" @@ -4991,7 +4565,7 @@ dependencies = [ "checksum rand 0.5.5 (registry+https://github.com/rust-lang/crates.io-index)" = "e464cd887e869cddcae8792a4ee31d23c7edd516700695608f5b98c67ee0131c" "checksum rand_core 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "edecf0f94da5551fc9b492093e30b041a891657db7940ee221f9d2f66e82eef2" "checksum rayon 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "485541959c8ecc49865526fe6c4de9653dd6e60d829d6edf0be228167b60372d" -"checksum rayon-core 1.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b055d1e92aba6877574d8fe604a63c8b5df60f60e5982bf7ccbb1338ea527356" +"checksum rayon-core 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9d24ad214285a7729b174ed6d3bcfcb80177807f959d95fafd5bfc5c4f201ac8" "checksum redox_syscall 0.1.17 (registry+https://github.com/rust-lang/crates.io-index)" = "29dbdfd4b9df8ab31dec47c6087b7b13cbf4a776f335e4de8efba8288dda075b" "checksum redox_termios 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7e891cfe48e9100a70a3b6eb652fef28920c117d366339687bd5576160db0f76" "checksum ref_filter_map 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2b5ceb840e4009da4841ed22a15eb49f64fdd00a2138945c5beacf506b2fb5ed" @@ -5003,13 +4577,16 @@ dependencies = [ "checksum rust-webvr 0.9.10 (registry+https://github.com/rust-lang/crates.io-index)" = "9629ce5b5c3cda05259d225e639851daf39c55c170358d3056205dd205deaab2" "checksum rust-webvr-api 0.9.2 (registry+https://github.com/rust-lang/crates.io-index)" = "712e22ba3c03a7075b40842ae91029a0ab96a81f95e97c0cf623800ec0cbac07" "checksum rustc-demangle 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "3058a43ada2c2d0b92b3ae38007a2d0fa5e9db971be260e0171408a4ff471c95" +"checksum rustc-serialize 0.3.24 (registry+https://github.com/rust-lang/crates.io-index)" = "dcf128d1287d2ea9d80910b5f1120d0b8eede3fbf1abe91c40d39ea7d51e6fda" +"checksum rustc_version 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "c5f5376ea5e30ce23c03eb77cbe4962b988deead10910c372b226388b594c084" "checksum safemem 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e27a8b19b835f7aea908818e871f5cc3a5a186550c30773be987e155e8163d8f" "checksum same-file 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "cfb6eded0b06a0b512c8ddbcf04089138c9b4362c2f696f3c3d76039d68f3637" "checksum scoped_threadpool 0.1.7 (registry+https://github.com/rust-lang/crates.io-index)" = "3ef399c8893e8cb7aa9696e895427fab3a6bf265977bb96e126f24ddd2cda85a" "checksum scopeguard 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c79eb2c3ac4bc2507cda80e7f3ac5b88bd8eae4c0914d5663e6a8933994be918" -"checksum serde 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)" = "15c141fc7027dd265a47c090bf864cf62b42c4d228bbcf4e51a0c9e2b0d3f7ef" +"checksum semver 0.1.20 (registry+https://github.com/rust-lang/crates.io-index)" = "d4f410fedcf71af0345d7607d246e7ad15faaadd49d240ee3b24e5dc21a820ac" +"checksum serde 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)" = "e9a2d9a9ac5120e0f768801ca2b58ad6eec929dc9d1d616c162f208869c2ce95" "checksum serde_bytes 0.10.4 (registry+https://github.com/rust-lang/crates.io-index)" = "adb6e51a6b3696b301bc221d785f898b4457c619b51d7ce195a6d20baecb37b3" -"checksum serde_derive 1.0.80 (registry+https://github.com/rust-lang/crates.io-index)" = "225de307c6302bec3898c51ca302fc94a7a1697ef0845fcee6448f33c032249c" +"checksum serde_derive 1.0.66 (registry+https://github.com/rust-lang/crates.io-index)" = "0a90213fa7e0f5eac3f7afe2d5ff6b088af515052cc7303bd68c7e3b91a3fb79" "checksum serde_json 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)" = "5c508584d9913df116b91505eec55610a2f5b16e9ed793c46e4d0152872b3e74" "checksum servo-egl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "21069a884c33fe6ee596975e1f3849ed88c4ec857fbaf11d33672d8ebe051217" "checksum servo-fontconfig 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "93f799b649b4a2bf362398910eca35240704c7e765e780349b2bb1070d892262" @@ -5021,18 +4598,17 @@ dependencies = [ "checksum servo-media-player 0.1.0 (git+https://github.com/servo/media)" = "" "checksum servo-skia 0.30000019.1 (registry+https://github.com/rust-lang/crates.io-index)" = "82eddddcf9512dd7c60eccdb486e60e5bd4930afaa4da2d7d4afdff75950fb88" "checksum servo_media_derive 0.1.0 (git+https://github.com/servo/media)" = "" -"checksum sha-1 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "51b9d1f3b5de8a167ab06834a7c883bd197f2191e1dda1a22d9ccfeedbf9aded" -"checksum sha1 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2579985fda508104f7587689507983eadd6a6e84dd35d6d115361f530916fa0d" +"checksum sha1 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "cc30b1e1e8c40c121ca33b86c23308a090d19974ef001b4bf6e61fd1a0fb095c" "checksum shared_library 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8254bf098ce4d8d7cc7cc6de438c5488adc5297e5b7ffef88816c0a91bd289c1" "checksum sig 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c6649e43c1a1e68d29ed56d0dc3b5b6cf3b901da77cf107c4066b9e3da036df5" "checksum signpost 0.1.0 (git+https://github.com/pcwalton/signpost.git)" = "" "checksum siphasher 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "0df90a788073e8d0235a67e50441d47db7c8ad9debd91cbf43736a2a92d36537" +"checksum slab 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "17b4fcaed89ab08ef143da37bc52adbcc04d4a69014f4c1208d6b51f0c47bc23" "checksum slab 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5f9776d6b986f77b35c6cf846c11ad986ff128fe0b2b63a3628e3755e8d3102d" "checksum smallbitvec 2.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5c63726029f0069f88467873e47f392575f28f9f16b72ac65465263db4b3a13c" "checksum smallvec 0.6.3 (registry+https://github.com/rust-lang/crates.io-index)" = "26df3bb03ca5eac2e64192b723d51f56c1b1e0860e7c766281f4598f181acdc8" "checksum smithay-client-toolkit 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "2051bffc6cbf271176e8ba1527f801b6444567daee15951ff5152aaaf7777b2f" "checksum stable_deref_trait 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "15132e0e364248108c5e2c02e3ab539be8d6f5d52a01ca9bbf27ed657316f02b" -"checksum string 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "00caf261d6f90f588f8450b8e1230fa0d5be49ee6140fdfbcb55335aff350970" "checksum string_cache 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "25d70109977172b127fe834e5449e5ab1740b9ba49fa18a2020f509174f25423" "checksum string_cache_codegen 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)" = "35293b05cf1494e8ddd042a7df6756bf18d07f42d234f32e71dce8a7aabb0191" "checksum string_cache_shared 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "b1884d1bc09741d466d9b14e6d37ac89d6909cbcac41dd9ae982d4d063bbedfc" @@ -5040,7 +4616,6 @@ dependencies = [ "checksum swapper 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e454d048db5527d000bfddb77bd072bbf3a1e2ae785f16d9bd116e07c2ab45eb" "checksum syn 0.13.1 (registry+https://github.com/rust-lang/crates.io-index)" = "91b52877572087400e83d24b9178488541e3d535259e04ff17a63df1e5ceff59" "checksum syn 0.14.2 (registry+https://github.com/rust-lang/crates.io-index)" = "c67da57e61ebc7b7b6fff56bb34440ca3a83db037320b0507af4c10368deda7d" -"checksum syn 0.15.6 (registry+https://github.com/rust-lang/crates.io-index)" = "854b08a640fc8f54728fb95321e3ec485b365a97fe47609797c671addd1dde69" "checksum synstructure 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "98cad891cd238c98e1f0aec9f7c0f620aa696e4e5f7daba56ac67b5e86a6b049" "checksum tempfile 3.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "47776f63b85777d984a50ce49d6b9e58826b6a3766a449fc95bc66cd5663c15b" "checksum tendril 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9de21546595a0873061940d994bbbc5c35f024ae4fd61ec5c5b159115684f508" @@ -5053,28 +4628,14 @@ dependencies = [ "checksum threadpool 1.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "59f6d3eff89920113dac9db44dde461d71d01e88a5b57b258a0466c32b5d7fe1" "checksum time 0.1.37 (registry+https://github.com/rust-lang/crates.io-index)" = "ffd7ccbf969a892bf83f1e441126968a07a3941c24ff522a26af9f9f4585d1a3" "checksum tinyfiledialogs 3.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "d79833ca2c493c726ea6a7b651ba0ff8a790add5156cd11bf3743f346005c0c8" -"checksum tokio 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "fbb6a6e9db2702097bfdfddcb09841211ad423b86c75b5ddaca1d62842ac492c" -"checksum tokio-codec 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "881e9645b81c2ce95fcb799ded2c29ffb9f25ef5bef909089a420e5961dd8ccb" -"checksum tokio-current-thread 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "8fdfb899688ac16f618076bd09215edbfda0fd5dfecb375b6942636cb31fa8a7" -"checksum tokio-executor 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "84823b932d566bc3c6aa644df4ca36cb38593c50b7db06011fd4e12e31e4047e" -"checksum tokio-fs 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "b5cbe4ca6e71cb0b62a66e4e6f53a8c06a6eefe46cc5f665ad6f274c9906f135" -"checksum tokio-io 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "8d6cc2de7725863c86ac71b0b9068476fec50834f055a243558ef1655bbd34cb" -"checksum tokio-openssl 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "4646ae1fd623393de3d796ea53af75acd02938dd5579544fbd6d236d041978a6" -"checksum tokio-reactor 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8703a5762ff6913510dc64272c714c4389ffd8c4b3cf602879b8bd14ff06b604" -"checksum tokio-tcp 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5b4c329b47f071eb8a746040465fa751bd95e4716e98daef6a9b4e434c17d565" -"checksum tokio-threadpool 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "a5758cecb6e0633cea5d563ac07c975e04961690b946b04fd84e7d6445a8f6af" -"checksum tokio-timer 0.2.6 (registry+https://github.com/rust-lang/crates.io-index)" = "d03fa701f9578a01b7014f106b47f0a363b4727a7f3f75d666e312ab7acbbf1c" -"checksum tokio-udp 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "da941144b816d0dcda4db3a1ba87596e4df5e860a72b70783fe435891f80601c" -"checksum tokio-uds 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "424c1ed15a0132251813ccea50640b224c809d6ceafb88154c1a8775873a0e89" "checksum toml 0.4.5 (registry+https://github.com/rust-lang/crates.io-index)" = "a7540f4ffc193e0d3c94121edb19b055670d369f77d5804db11ae053a45b6e7e" +"checksum traitobject 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "efd1f82c56340fdf16f2a953d7bda4f8fdffba13d93b00844c25572110b26079" "checksum truetype 0.26.0 (registry+https://github.com/rust-lang/crates.io-index)" = "acec30350633d6dac9dc1a625786b6cbe9150664be941aac2c35ad7199eab877" -"checksum try-lock 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e604eb7b43c06650e854be16a2a03155743d3752dd1c943f6829e26b7a36e382" -"checksum typenum 1.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "612d636f949607bdf9b123b4a6f6d966dedf3ff669f7f045890d3a4a73948169" +"checksum typeable 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1410f6f91f21d1612654e7cc69193b0334f909dcf2c790c4826254fbb86f8887" "checksum ucd 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fe4fa6e588762366f1eb4991ce59ad1b93651d0b769dfb4e4d1c5c4b943d1159" "checksum ucd-util 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "fd2be2d6639d0f8fe6cdda291ad456e23629558d466e2789d2c3e9892bda285d" "checksum uluru 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d2606e9192f308ddc4f0b3c5d1bf3400e28a70fff956e9d9f46d23b094746d9f" -"checksum unicase 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "7f4765f83163b74f957c797ad9253caf97f103fb064d3999aea9568d09fc8a33" -"checksum unicase 2.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "284b6d3db520d67fbe88fd778c21510d1b0ba4a551e5d0fbb023d33405f6de8a" +"checksum unicase 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "13a5906ca2b98c799f4b1ab4557b76367ebd6ae5ef14930ec841c74aed5f3764" "checksum unicode-bidi 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "a6a2c4e3710edd365cd7e78383153ed739fa31af19f9172f72d3575060f5a43a" "checksum unicode-normalization 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "51ccda9ef9efa3f7ef5d91e8f9b83bbe6955f9bf86aec89d5cce2c874625920f" "checksum unicode-script 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e8bd7bbf020b2885113e6304f68bcc33881c5552657c58d4e9699cd1b6606e81" @@ -5082,7 +4643,7 @@ dependencies = [ "checksum unicode-width 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "bf3a113775714a22dcb774d8ea3655c53a32debae63a063acc00a91cc586245f" "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unreachable 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "382810877fe448991dfc7f0dd6e3ae5d58088fd0ea5e35189655f84e6814fa56" -"checksum url 1.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2a321979c09843d272956e73700d12c4e7d3d92b2ee112b31548aef0d4efc5a6" +"checksum url 1.6.1 (registry+https://github.com/rust-lang/crates.io-index)" = "23ef1b2df9b1541244318407f1ed96e754dab6efac4121dc1c4c16d38daf215e" "checksum url_serde 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "74e7d099f1ee52f823d4bdd60c93c3602043c728f5db3b97bdb548467f7bddea" "checksum user32-sys 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "4ef4711d107b21b410a3a974b1204d9accc8b10dad75d8324b5d755de1617d47" "checksum utf-8 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b6f923c601c7ac48ef1d66f7d5b5b2d9a7ba9c51333ab75a3ddf8d0309185a56" @@ -5090,28 +4651,26 @@ dependencies = [ "checksum uuid 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "d4670e1e935f7edd193a413f802e2ee52274aed62a09ccaab1656515c9c53a66" "checksum vcpkg 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "9e0a7d8bed3178a8fb112199d466eeca9ed09a14ba8ad67718179b4fd5487d0b" "checksum vec_map 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "887b5b631c2ad01628bbbaa7dd4c869f80d3186688f8d0b6f58774fbe324988c" -"checksum version_check 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "7716c242968ee87e5542f8021178248f267f295a5c4803beae8b8b7fd9bc6051" "checksum void 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "6a02e4885ed3bc0f2de90ea6dd45ebcbb66dacffe03547fadbb0eeae2770887d" "checksum walkdir 2.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "63636bd0eb3d00ccb8b9036381b526efac53caf112b7783b730ab3f8e44da369" -"checksum want 0.0.6 (registry+https://github.com/rust-lang/crates.io-index)" = "797464475f30ddb8830cc529aaaae648d581f99e2036a928877dfde027ddf6b3" "checksum wayland-client 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)" = "0f3ed65542a0be13ea0fdcc55c9a011fcc44c3882e6e1a9b4dfddb25182897dd" "checksum wayland-commons 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4ac5c79f1d050f4047a82ddce77acda026c142c0023e7b7e20eea5ad76fb7dbf" "checksum wayland-protocols 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)" = "be56e3d80559177a70bc78f9396fbe1705b7baed4951ae6e34d28bb59681b1a8" "checksum wayland-scanner 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)" = "93cf4ef48caedf3fc1a9b2bf0df64e6d425bd628b85830a08432dd25b61de17c" "checksum wayland-sys 0.20.10 (registry+https://github.com/rust-lang/crates.io-index)" = "d2dbe7b51c16b8a8153806aaa21f346333074482bb57bc5cb059cc828f8c6842" -"checksum webdriver 0.37.0 (registry+https://github.com/rust-lang/crates.io-index)" = "426afe4e337c88343569b65ed0d84c44655c1d66c5570f3e50da98b64c38298f" +"checksum webdriver 0.35.1 (registry+https://github.com/rust-lang/crates.io-index)" = "0c6d14048509ec30805ee10b9d610d3d1987e560f5d3be5c599c2c812a34bbfe" "checksum webrender 0.57.2 (git+https://github.com/servo/webrender)" = "" "checksum webrender_api 0.57.2 (git+https://github.com/servo/webrender)" = "" "checksum which 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4be6cfa54dab45266e98b5d7be2f8ce959ddd49abd141a05d52dce4b07f803bb" "checksum winapi 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a" -"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" +"checksum winapi 0.3.5 (registry+https://github.com/rust-lang/crates.io-index)" = "773ef9dcc5f24b7d850d0ff101e542ff24c3b090a9768e03ff889fdef41f00fd" "checksum winapi-build 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "2d315eee3b34aca4797b2da6b13ed88266e6d612562a0c46390af8299fc699bc" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" "checksum wincolor 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "eeb06499a3a4d44302791052df005d5232b927ed1a9658146d842165c4de7767" "checksum winit 0.17.0 (registry+https://github.com/rust-lang/crates.io-index)" = "51fe58cceab36bef11fcb57d0a86f4cdf0c8668ad51fdbc6d48efa6b2db0cddd" "checksum winres 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "27d9192d6356d7efe8405dec6c5506b67543cf64b6049968f39f4c4623b4f25d" -"checksum ws 0.7.9 (registry+https://github.com/rust-lang/crates.io-index)" = "329d3e6dd450a9c5c73024e1047f0be7e24121a68484eb0b5368977bee3cf8c3" +"checksum ws 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)" = "89c48c53bf9dee34411a08993c10b879c36e105d609b46e25673befe3a5c1320" "checksum ws2_32-sys 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "d59cefebd0c892fa2dd6de581e937301d8552cb44489cdff035c6187cb63fa5e" "checksum x11 2.17.3 (registry+https://github.com/rust-lang/crates.io-index)" = "7e5c4ac579b5d324dc4add02312b5d0e3e0218521e2d5779d526ac39ee4bb171" "checksum x11-clipboard 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d8617c6185c96e5fcf57ff156496d73c9c82b7f09a5fea21b518dd32c10e2e05" diff --git a/Cargo.toml b/Cargo.toml index f20f4d1194ed..069fd75fc96b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,11 @@ members = [ "ports/servo", "ports/libsimpleservo/", - "ports/libmlservo/", + "tests/unit/*", +] +default-members = [ + "ports/servo", + "ports/libsimpleservo/", "tests/unit/*", ] exclude = [".cargo"] diff --git a/README.md b/README.md index 571b697a356d..1b45ee9a44a1 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ Please select your operating system: ``` sh brew install automake autoconf@2.13 pkg-config python cmake yasm llvm -brew install gstreamer gst-plugins-base gst-plugins-good gst-plugins-bad gst-libav gst-rtsp-server --with-orc --with-libogg --with-opus --with-pango --with-theora --with-libvorbis +brew install gstreamer gst-plugins-base gst-plugins-good gst-plugins-bad gst-plugins-ugly gst-libav gst-rtsp-server --with-orc -with-libogg --with-opus --with-pango --with-theora --with-libvorbis pip install virtualenv ``` #### On macOS (MacPorts) @@ -221,35 +221,19 @@ settings for the installer are fine). 5. Install Visual Studio Community 2017 (https://www.visualstudio.com/vs/community/). You MUST add "Visual C++" to the list of installed components. It is not on by default. Visual Studio 2017 MUST installed to the default location or mach.bat will not find it. - -##### [Optional] Install LLVM for faster link times - -You may experience much faster builds on Windows by following these steps. (Related Rust issue: https://github.com/rust-lang/rust/issues/37543) - -1. Download the latest version of LLVM (https://releases.llvm.org/). -2. Run the installer and choose to add LLVM to the system PATH. -3. Add the following to your Cargo config (Found at `%USERPROFILE%\.cargo\config`). You may need to change the triple to match your environment. - -``` -[target.x86_64-pc-windows-msvc] -linker = "lld-link.exe" -``` - -##### Troubleshooting a Windows environment - > If you encountered errors with the environment above, do the following for a workaround: > 1. Download and install [Build Tools for Visual Studio 2017](https://www.visualstudio.com/thank-you-downloading-visual-studio/?sku=BuildTools&rel=15) > 2. Install `python2.7 x86-x64` and `virtualenv` > 3. Run `mach.bat build -d`. >If you have troubles with `x64 type` prompt as `mach.bat` set by default: -> 1. You may need to choose and launch the type manually, such as `x86_x64 Cross Tools Command Prompt for VS 2017` in the Windows menu.) +> 1. you may need to choose and launch the type manually, such as `x86_x64 Cross Tools Command Prompt for VS 2017` in the Windows menu.) > 2. `cd to/the/path/servo` > 3. `python mach build -d` #### Cross-compilation for Android -Run `./mach bootstrap-android --build` to get Android-specific tools. See wiki for +Run `./mach bootstrap-android` to get Android-specific tools. See wiki for [details](https://github.com/servo/servo/wiki/Building-for-Android). ## The Rust compiler @@ -358,4 +342,4 @@ There are lots of mach commands you can use. You can list them with `./mach --help`. -The generated documentation can be found on https://doc.servo.org/servo/index.html +The generated documentation can be found on http://doc.servo.org/servo/index.html diff --git a/appveyor.yml b/appveyor.yml index 5092ebf910ce..6be6ea70418e 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -55,8 +55,8 @@ install: - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin - set PKG_CONFIG_PATH=%PKG_CONFIG_PATH%;C:\gstreamer\1.0\x86_64\lib\pkgconfig - rustup -V - - rustc --version - - cargo --version + - mach rustc --version + - mach cargo --version # Uncomment these lines to expose RDP access information to the build machine in the build log. #init: diff --git a/components/allocator/Cargo.toml b/components/allocator/Cargo.toml index 037e7e6e9ae5..1fb3299e5919 100644 --- a/components/allocator/Cargo.toml +++ b/components/allocator/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_allocator" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/allocator/lib.rs b/components/allocator/lib.rs index 3ce50be8b227..676148926140 100644 --- a/components/allocator/lib.rs +++ b/components/allocator/lib.rs @@ -7,14 +7,12 @@ #[global_allocator] static ALLOC: Allocator = Allocator; -pub use crate::platform::*; - -#[cfg(not(windows))] -pub use jemalloc_sys; +pub use platform::*; #[cfg(not(windows))] mod platform { - use jemalloc_sys as ffi; + extern crate jemalloc_sys as ffi; + use std::alloc::{GlobalAlloc, Layout}; use std::os::raw::{c_int, c_void}; @@ -25,30 +23,38 @@ mod platform { /// Memory allocation APIs compatible with libc pub mod libc_compat { - pub use super::ffi::{free, malloc, realloc}; + pub use super::ffi::{malloc, realloc, free}; } pub struct Allocator; // The minimum alignment guaranteed by the architecture. This value is used to // add fast paths for low alignment values. - #[cfg(all(any( - target_arch = "arm", - target_arch = "mips", - target_arch = "mipsel", - target_arch = "powerpc" - )))] + #[cfg( + all( + any( + target_arch = "arm", + target_arch = "mips", + target_arch = "mipsel", + target_arch = "powerpc" + ) + ) + )] const MIN_ALIGN: usize = 8; - #[cfg(all(any( - target_arch = "x86", - target_arch = "x86_64", - target_arch = "aarch64", - target_arch = "powerpc64", - target_arch = "powerpc64le", - target_arch = "mips64", - target_arch = "s390x", - target_arch = "sparc64" - )))] + #[cfg( + all( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "aarch64", + target_arch = "powerpc64", + target_arch = "powerpc64le", + target_arch = "mips64", + target_arch = "s390x", + target_arch = "sparc64" + ) + ) + )] const MIN_ALIGN: usize = 16; fn layout_to_flags(align: usize, size: usize) -> c_int { @@ -98,8 +104,10 @@ mod platform { #[cfg(windows)] mod platform { - use kernel32::{GetProcessHeap, HeapSize, HeapValidate}; + extern crate kernel32; + pub use std::alloc::System as Allocator; + use self::kernel32::{GetProcessHeap, HeapSize, HeapValidate}; use std::os::raw::c_void; /// Get the size of a heap block. diff --git a/components/atoms/Cargo.toml b/components/atoms/Cargo.toml index 493088f7f246..9e6e07899e6b 100644 --- a/components/atoms/Cargo.toml +++ b/components/atoms/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_atoms" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false build = "build.rs" diff --git a/components/atoms/build.rs b/components/atoms/build.rs index 3272683c2ca8..309e111dbd7a 100644 --- a/components/atoms/build.rs +++ b/components/atoms/build.rs @@ -2,9 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate string_cache_codegen; + use std::env; use std::fs::File; -use std::io::{BufRead, BufReader}; +use std::io::{BufReader, BufRead}; use std::path::Path; fn main() { diff --git a/components/atoms/lib.rs b/components/atoms/lib.rs index 87009b13b674..c1da7167bde1 100644 --- a/components/atoms/lib.rs +++ b/components/atoms/lib.rs @@ -2,4 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate string_cache; + include!(concat!(env!("OUT_DIR"), "/atom.rs")); diff --git a/components/atoms/static_atoms.txt b/components/atoms/static_atoms.txt index 081c8c314cd4..7fbd043dc0fe 100644 --- a/components/atoms/static_atoms.txt +++ b/components/atoms/static_atoms.txt @@ -18,7 +18,6 @@ cursive date datetime-local dir -durationchange email emptied ended @@ -66,20 +65,13 @@ range readystatechange reftest-wait reset -resize right rtl sans-serif -safe-area-inset-top -safe-area-inset-bottom -safe-area-inset-left -safe-area-inset-right scan screen scroll-position search -seeked -seeking select serif statechange @@ -92,7 +84,6 @@ time timeupdate toggle transitionend -unhandledrejection unload url waiting diff --git a/components/bluetooth/Cargo.toml b/components/bluetooth/Cargo.toml index d6dbf63db4a5..912715030900 100644 --- a/components/bluetooth/Cargo.toml +++ b/components/bluetooth/Cargo.toml @@ -3,7 +3,6 @@ name = "bluetooth" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -13,6 +12,7 @@ path = "lib.rs" [dependencies] bitflags = "1.0" bluetooth_traits = {path = "../bluetooth_traits"} +device = {git = "https://github.com/servo/devices", features = ["bluetooth-test"]} embedder_traits = {path = "../embedder_traits"} ipc-channel = "0.11" log = "0.4" @@ -20,11 +20,5 @@ servo_config = {path = "../config"} servo_rand = {path = "../rand"} uuid = {version = "0.6", features = ["v4"]} -[features] -disable-native-bluetooth = [] - -[target.'cfg(feature = "disable-native-bluetooth")'.dependencies] -device = {git = "https://github.com/servo/devices", default-features = false, features = ["bluetooth-test"]} - -[target.'cfg(not(feature = "disable-native-bluetooth"))'.dependencies] -device = {git = "https://github.com/servo/devices", features = ["bluetooth-test"]} +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"]} diff --git a/components/bluetooth/lib.rs b/components/bluetooth/lib.rs index e563c8fd8a4e..300927d440f8 100644 --- a/components/bluetooth/lib.rs +++ b/components/bluetooth/lib.rs @@ -4,25 +4,30 @@ #[macro_use] extern crate bitflags; +extern crate bluetooth_traits; +extern crate device; +extern crate embedder_traits; +extern crate ipc_channel; #[macro_use] extern crate log; +extern crate servo_config; +extern crate servo_rand; +extern crate uuid; pub mod test; -use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; -use bluetooth_traits::scanfilter::{ - BluetoothScanfilter, BluetoothScanfilterSequence, RequestDeviceoptions, -}; use bluetooth_traits::{BluetoothCharacteristicMsg, BluetoothDescriptorMsg, BluetoothServiceMsg}; use bluetooth_traits::{BluetoothDeviceMsg, BluetoothRequest, BluetoothResponse, GATTType}; use bluetooth_traits::{BluetoothError, BluetoothResponseResult, BluetoothResult}; +use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; +use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence, RequestDeviceoptions}; use device::bluetooth::{BluetoothAdapter, BluetoothDevice, BluetoothGATTCharacteristic}; use device::bluetooth::{BluetoothGATTDescriptor, BluetoothGATTService}; use embedder_traits::{EmbedderMsg, EmbedderProxy}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use servo_config::opts; use servo_config::prefs::PREFS; -use servo_rand::{self, Rng}; +use servo_rand::Rng; use std::borrow::ToOwned; use std::collections::{HashMap, HashSet}; use std::string::String; @@ -69,8 +74,7 @@ impl BluetoothThreadFactory for IpcSender { BluetoothAdapter::init() } else { BluetoothAdapter::init_mock() - } - .ok(); + }.ok(); thread::Builder::new() .name("BluetoothThread".to_owned()) .spawn(move || { @@ -461,10 +465,8 @@ impl BluetoothManager { }; services.retain(|s| { - !uuid_is_blocklisted(&s.get_uuid().unwrap_or(String::new()), Blocklist::All) && self - .allowed_services - .get(device_id) - .map_or(false, |uuids| { + !uuid_is_blocklisted(&s.get_uuid().unwrap_or(String::new()), Blocklist::All) && + self.allowed_services.get(device_id).map_or(false, |uuids| { uuids.contains(&s.get_uuid().unwrap_or(String::new())) }) }); @@ -554,9 +556,9 @@ impl BluetoothManager { } fn characteristic_is_cached(&self, characteristic_id: &str) -> bool { - self.cached_characteristics.contains_key(characteristic_id) && self - .characteristic_to_service - .contains_key(characteristic_id) + self.cached_characteristics.contains_key(characteristic_id) && + self.characteristic_to_service + .contains_key(characteristic_id) } // Descriptor diff --git a/components/bluetooth/test.rs b/components/bluetooth/test.rs index 0056f06767c8..d7410719608f 100644 --- a/components/bluetooth/test.rs +++ b/components/bluetooth/test.rs @@ -2,14 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::BluetoothManager; +use BluetoothManager; use device::bluetooth::{BluetoothAdapter, BluetoothDevice}; -use device::bluetooth::{ - BluetoothGATTCharacteristic, BluetoothGATTDescriptor, BluetoothGATTService, -}; +use device::bluetooth::{BluetoothGATTCharacteristic, BluetoothGATTDescriptor, BluetoothGATTService}; use std::borrow::ToOwned; use std::cell::RefCell; -use std::collections::{HashMap, HashSet}; +use std::collections::{HashSet, HashMap}; use std::error::Error; use std::string::String; use uuid::Uuid; @@ -137,7 +135,7 @@ fn generate_id() -> Uuid { } // Set the adapter's name, is_powered and is_discoverable attributes -fn set_adapter(adapter: &BluetoothAdapter, adapter_name: String) -> Result<(), Box> { +fn set_adapter(adapter: &BluetoothAdapter, adapter_name: String) -> Result<(), Box> { adapter.set_name(adapter_name)?; adapter.set_powered(true)?; adapter.set_discoverable(true)?; @@ -149,7 +147,7 @@ fn create_device( adapter: &BluetoothAdapter, name: String, address: String, -) -> Result> { +) -> Result> { let device = BluetoothDevice::create_mock_device(adapter.clone(), generate_id().to_string())?; device.set_name(Some(name))?; device.set_address(address)?; @@ -163,7 +161,7 @@ fn create_device_with_uuids( name: String, address: String, uuids: Vec, -) -> Result> { +) -> Result> { let device = create_device(adapter, name, address)?; device.set_uuids(uuids)?; Ok(device) @@ -173,7 +171,7 @@ fn create_device_with_uuids( fn create_service( device: &BluetoothDevice, uuid: String, -) -> Result> { +) -> Result> { let service = BluetoothGATTService::create_mock_service(device.clone(), generate_id().to_string())?; service.set_uuid(uuid)?; @@ -184,7 +182,7 @@ fn create_service( fn create_characteristic( service: &BluetoothGATTService, uuid: String, -) -> Result> { +) -> Result> { let characteristic = BluetoothGATTCharacteristic::create_mock_characteristic( service.clone(), generate_id().to_string(), @@ -198,7 +196,7 @@ fn create_characteristic_with_value( service: &BluetoothGATTService, uuid: String, value: Vec, -) -> Result> { +) -> Result> { let characteristic = create_characteristic(service, uuid)?; characteristic.set_value(value)?; Ok(characteristic) @@ -208,7 +206,7 @@ fn create_characteristic_with_value( fn create_descriptor( characteristic: &BluetoothGATTCharacteristic, uuid: String, -) -> Result> { +) -> Result> { let descriptor = BluetoothGATTDescriptor::create_mock_descriptor( characteristic.clone(), generate_id().to_string(), @@ -222,7 +220,7 @@ fn create_descriptor_with_value( characteristic: &BluetoothGATTCharacteristic, uuid: String, value: Vec, -) -> Result> { +) -> Result> { let descriptor = create_descriptor(characteristic, uuid)?; descriptor.set_value(value)?; Ok(descriptor) @@ -231,7 +229,7 @@ fn create_descriptor_with_value( fn create_heart_rate_service( device: &BluetoothDevice, empty: bool, -) -> Result> { +) -> Result> { // Heart Rate Service let heart_rate_service = create_service(device, HEART_RATE_SERVICE_UUID.to_owned())?; @@ -274,7 +272,7 @@ fn create_heart_rate_service( fn create_generic_access_service( device: &BluetoothDevice, empty: bool, -) -> Result> { +) -> Result> { // Generic Access Service let generic_access_service = create_service(device, GENERIC_ACCESS_SERVICE_UUID.to_owned())?; @@ -296,16 +294,14 @@ fn create_generic_access_service( NUMBER_OF_DIGITALS_UUID.to_owned(), vec![49], )?; - number_of_digitals_descriptor_1 - .set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?; + number_of_digitals_descriptor_1.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?; let number_of_digitals_descriptor_2 = create_descriptor_with_value( &device_name_characteristic, NUMBER_OF_DIGITALS_UUID.to_owned(), vec![50], )?; - number_of_digitals_descriptor_2 - .set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?; + number_of_digitals_descriptor_2.set_flags(vec![READ_FLAG.to_string(), WRITE_FLAG.to_string()])?; // Characteristic User Description Descriptor let _characteristic_user_description = create_descriptor_with_value( @@ -335,7 +331,7 @@ fn create_generic_access_service( fn create_heart_rate_device( adapter: &BluetoothAdapter, empty: bool, -) -> Result> { +) -> Result> { // Heart Rate Device let heart_rate_device = create_device_with_uuids( adapter, @@ -362,7 +358,7 @@ fn create_heart_rate_device( fn create_missing_characterisitc_heart_rate_device( adapter: &BluetoothAdapter, -) -> Result<(), Box> { +) -> Result<(), Box> { let heart_rate_device_empty = create_heart_rate_device(adapter, true)?; let _generic_access_service_empty = @@ -375,7 +371,7 @@ fn create_missing_characterisitc_heart_rate_device( fn create_missing_descriptor_heart_rate_device( adapter: &BluetoothAdapter, -) -> Result<(), Box> { +) -> Result<(), Box> { let heart_rate_device_empty = create_heart_rate_device(adapter, true)?; let generic_access_service_empty = @@ -399,7 +395,7 @@ fn create_missing_descriptor_heart_rate_device( Ok(()) } -fn create_two_heart_rate_services_device(adapter: &BluetoothAdapter) -> Result<(), Box> { +fn create_two_heart_rate_services_device(adapter: &BluetoothAdapter) -> Result<(), Box> { let heart_rate_device_empty = create_heart_rate_device(adapter, true)?; heart_rate_device_empty.set_uuids(vec![ @@ -435,7 +431,7 @@ fn create_two_heart_rate_services_device(adapter: &BluetoothAdapter) -> Result<( Ok(()) } -fn create_blocklisted_device(adapter: &BluetoothAdapter) -> Result<(), Box> { +fn create_blocklisted_device(adapter: &BluetoothAdapter) -> Result<(), Box> { let connectable_device = create_device_with_uuids( adapter, CONNECTABLE_DEVICE_NAME.to_owned(), @@ -490,7 +486,7 @@ fn create_blocklisted_device(adapter: &BluetoothAdapter) -> Result<(), Box Result<(), Box> { +fn create_glucose_heart_rate_devices(adapter: &BluetoothAdapter) -> Result<(), Box> { let glucose_devie = create_device_with_uuids( adapter, GLUCOSE_DEVICE_NAME.to_owned(), @@ -517,7 +513,7 @@ fn create_glucose_heart_rate_devices(adapter: &BluetoothAdapter) -> Result<(), B Ok(()) } -pub fn test(manager: &mut BluetoothManager, data_set_name: String) -> Result<(), Box> { +pub fn test(manager: &mut BluetoothManager, data_set_name: String) -> Result<(), Box> { let may_existing_adapter = manager.get_or_create_adapter(); let adapter = match may_existing_adapter.as_ref() { Some(adapter) => adapter, diff --git a/components/bluetooth_traits/Cargo.toml b/components/bluetooth_traits/Cargo.toml index d8cb171de3cd..5446a996ebfa 100644 --- a/components/bluetooth_traits/Cargo.toml +++ b/components/bluetooth_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "bluetooth_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -15,3 +14,6 @@ ipc-channel = "0.11" regex = "1.0" serde = "1.0" embedder_traits = { path = "../embedder_traits" } + +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"] } diff --git a/components/bluetooth_traits/lib.rs b/components/bluetooth_traits/lib.rs index 4733937d105a..0925234666b0 100644 --- a/components/bluetooth_traits/lib.rs +++ b/components/bluetooth_traits/lib.rs @@ -2,16 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate embedder_traits; +extern crate ipc_channel; +extern crate regex; #[macro_use] extern crate serde; pub mod blocklist; pub mod scanfilter; -use crate::scanfilter::{BluetoothScanfilterSequence, RequestDeviceoptions}; use ipc_channel::ipc::IpcSender; +use scanfilter::{BluetoothScanfilterSequence, RequestDeviceoptions}; -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum BluetoothError { Type(String), Network, @@ -21,7 +24,7 @@ pub enum BluetoothError { InvalidState, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum GATTType { PrimaryService, Characteristic, @@ -29,21 +32,21 @@ pub enum GATTType { Descriptor, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothDeviceMsg { // Bluetooth Device properties pub id: String, pub name: Option, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothServiceMsg { pub uuid: String, pub is_primary: bool, pub instance_id: String, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothCharacteristicMsg { // Characteristic pub uuid: String, @@ -60,7 +63,7 @@ pub struct BluetoothCharacteristicMsg { pub writable_auxiliaries: bool, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothDescriptorMsg { pub uuid: String, pub instance_id: String, @@ -76,7 +79,7 @@ pub type BluetoothResult = Result; pub type BluetoothResponseResult = Result; -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum BluetoothRequest { RequestDevice(RequestDeviceoptions, IpcSender), GATTServerConnect(String, IpcSender), @@ -104,7 +107,7 @@ pub enum BluetoothRequest { Exit, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum BluetoothResponse { RequestDevice(BluetoothDeviceMsg), GATTServerConnect(bool), diff --git a/components/bluetooth_traits/scanfilter.rs b/components/bluetooth_traits/scanfilter.rs index 099b9372a4e6..cde3d172a25b 100644 --- a/components/bluetooth_traits/scanfilter.rs +++ b/components/bluetooth_traits/scanfilter.rs @@ -10,7 +10,7 @@ use std::slice::Iter; // That leaves 29 bytes for the name. const MAX_NAME_LENGTH: usize = 29; -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct ServiceUUIDSequence(Vec); impl ServiceUUIDSequence { @@ -26,7 +26,7 @@ impl ServiceUUIDSequence { type ManufacturerData = HashMap, Vec)>; type ServiceData = HashMap, Vec)>; -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothScanfilter { name: Option, name_prefix: String, @@ -83,7 +83,7 @@ impl BluetoothScanfilter { } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct BluetoothScanfilterSequence(Vec); impl BluetoothScanfilterSequence { @@ -110,7 +110,7 @@ impl BluetoothScanfilterSequence { } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct RequestDeviceoptions { filters: BluetoothScanfilterSequence, optional_services: ServiceUUIDSequence, diff --git a/components/canvas/Cargo.toml b/components/canvas/Cargo.toml index e411e415e992..4006947acf66 100644 --- a/components/canvas/Cargo.toml +++ b/components/canvas/Cargo.toml @@ -3,7 +3,6 @@ name = "canvas" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -17,15 +16,14 @@ webgl_backtrace = ["canvas_traits/webgl_backtrace"] azure = {git = "https://github.com/servo/rust-azure"} canvas_traits = {path = "../canvas_traits"} compositing = {path = "../compositing"} -cssparser = "0.25" +cssparser = "0.24" euclid = "0.19" fnv = "1.0" -gleam = "0.6.4" +gleam = "0.6" ipc-channel = "0.11" log = "0.4" num-traits = "0.2" offscreen_gl_context = {version = "0.21", features = ["serde", "osmesa"]} -pixels = {path = "../pixels"} serde_bytes = "0.10" servo_config = {path = "../config"} webrender = {git = "https://github.com/servo/webrender"} diff --git a/components/canvas/canvas_data.rs b/components/canvas/canvas_data.rs index d07ee2cd9cf5..b1768fe8744d 100644 --- a/components/canvas/canvas_data.rs +++ b/components/canvas/canvas_data.rs @@ -3,21 +3,20 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure::AzFloat; -use azure::azure_hl::SurfacePattern; use azure::azure_hl::{AntialiasMode, CapStyle, CompositionOp, JoinStyle}; -use azure::azure_hl::{ - BackendType, DrawOptions, DrawTarget, Pattern, StrokeOptions, SurfaceFormat, -}; +use azure::azure_hl::{BackendType, DrawOptions, DrawTarget, Pattern, StrokeOptions, SurfaceFormat}; use azure::azure_hl::{Color, ColorPattern, DrawSurfaceOptions, Filter, PathBuilder}; use azure::azure_hl::{ExtendMode, GradientStop, LinearGradientPattern, RadialGradientPattern}; +use azure::azure_hl::SurfacePattern; use canvas_traits::canvas::*; use cssparser::RGBA; -use euclid::{Point2D, Rect, Size2D, Transform2D, Vector2D}; -use ipc_channel::ipc::IpcSender; +use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D}; +use ipc_channel::ipc::{IpcBytesSender, IpcSender}; use num_traits::ToPrimitive; use serde_bytes::ByteBuf; use std::mem; use std::sync::Arc; +use webrender_api; pub struct CanvasData<'a> { drawtarget: DrawTarget, @@ -36,10 +35,10 @@ pub struct CanvasData<'a> { impl<'a> CanvasData<'a> { pub fn new( - size: Size2D, + size: Size2D, webrender_api_sender: webrender_api::RenderApiSender, antialias: AntialiasMode, - canvas_id: CanvasId, + canvas_id: CanvasId ) -> CanvasData<'a> { let draw_target = CanvasData::create(size); let path_builder = draw_target.create_path_builder(); @@ -63,34 +62,22 @@ impl<'a> CanvasData<'a> { image_size: Size2D, dest_rect: Rect, source_rect: Rect, - smoothing_enabled: bool, + smoothing_enabled: bool ) { // We round up the floating pixel values to draw the pixels let source_rect = source_rect.ceil(); // It discards the extra pixels (if any) that won't be painted - let image_data = if Rect::from_size(image_size).contains_rect(&source_rect) { - pixels::get_rect(&image_data, image_size.to_u32(), source_rect.to_u32()).into() - } else { - image_data.into() - }; + let image_data = crop_image(image_data, image_size, source_rect); let writer = |draw_target: &DrawTarget| { - write_image( - &draw_target, - image_data, - source_rect.size, - dest_rect, - smoothing_enabled, - self.state.draw_options.composition, - self.state.draw_options.alpha, - ); + write_image(&draw_target, image_data, source_rect.size, dest_rect, + smoothing_enabled, self.state.draw_options.composition, + self.state.draw_options.alpha); }; if self.need_to_draw_shadow() { - let rect = Rect::new( - Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32), - Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32), - ); + let rect = Rect::new(Point2D::new(dest_rect.origin.x as f32, dest_rect.origin.y as f32), + Size2D::new(dest_rect.size.width as f32, dest_rect.size.height as f32)); self.draw_with_shadow(&rect, writer); } else { @@ -111,10 +98,7 @@ impl<'a> CanvasData<'a> { } pub fn fill_text(&self, text: String, x: f64, y: f64, max_width: Option) { - error!( - "Unimplemented canvas2d.fillText. Values received: {}, {}, {}, {:?}.", - text, x, y, max_width - ); + error!("Unimplemented canvas2d.fillText. Values received: {}, {}, {}, {:?}.", text, x, y, max_width); } pub fn fill_rect(&self, rect: &Rect) { @@ -122,8 +106,7 @@ impl<'a> CanvasData<'a> { return; // Paint nothing if gradient size is zero. } - let draw_rect = Rect::new( - rect.origin, + let draw_rect = Rect::new(rect.origin, match self.state.fill_style { Pattern::Surface(ref surface) => { let surface_size = surface.size(); @@ -131,29 +114,21 @@ impl<'a> CanvasData<'a> { (true, true) => rect.size, (true, false) => Size2D::new(rect.size.width, surface_size.height as f32), (false, true) => Size2D::new(surface_size.width as f32, rect.size.height), - (false, false) => { - Size2D::new(surface_size.width as f32, surface_size.height as f32) - }, + (false, false) => Size2D::new(surface_size.width as f32, surface_size.height as f32), } }, _ => rect.size, - }, + } ); if self.need_to_draw_shadow() { self.draw_with_shadow(&draw_rect, |new_draw_target: &DrawTarget| { - new_draw_target.fill_rect( - &draw_rect, - self.state.fill_style.to_pattern_ref(), - Some(&self.state.draw_options), - ); + new_draw_target.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(), + Some(&self.state.draw_options)); }); } else { - self.drawtarget.fill_rect( - &draw_rect, - self.state.fill_style.to_pattern_ref(), - Some(&self.state.draw_options), - ); + self.drawtarget.fill_rect(&draw_rect, self.state.fill_style.to_pattern_ref(), + Some(&self.state.draw_options)); } } @@ -168,40 +143,27 @@ impl<'a> CanvasData<'a> { if self.need_to_draw_shadow() { self.draw_with_shadow(&rect, |new_draw_target: &DrawTarget| { - new_draw_target.stroke_rect( - rect, - self.state.stroke_style.to_pattern_ref(), - &self.state.stroke_opts, - &self.state.draw_options, - ); + new_draw_target.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(), + &self.state.stroke_opts, &self.state.draw_options); }); } else if rect.size.width == 0. || rect.size.height == 0. { let cap = match self.state.stroke_opts.line_join { JoinStyle::Round => CapStyle::Round, - _ => CapStyle::Butt, + _ => CapStyle::Butt }; - let stroke_opts = StrokeOptions::new( - self.state.stroke_opts.line_width, - self.state.stroke_opts.line_join, - cap, - self.state.stroke_opts.miter_limit, - self.state.stroke_opts.mDashPattern, - ); - self.drawtarget.stroke_line( - rect.origin, - rect.bottom_right(), - self.state.stroke_style.to_pattern_ref(), - &stroke_opts, - &self.state.draw_options, - ); + let stroke_opts = + StrokeOptions::new(self.state.stroke_opts.line_width, + self.state.stroke_opts.line_join, + cap, + self.state.stroke_opts.miter_limit, + self.state.stroke_opts.mDashPattern); + self.drawtarget.stroke_line(rect.origin, rect.bottom_right(), + self.state.stroke_style.to_pattern_ref(), + &stroke_opts, &self.state.draw_options); } else { - self.drawtarget.stroke_rect( - rect, - self.state.stroke_style.to_pattern_ref(), - &self.state.stroke_opts, - &self.state.draw_options, - ); + self.drawtarget.stroke_rect(rect, self.state.stroke_style.to_pattern_ref(), + &self.state.stroke_opts, &self.state.draw_options); } } @@ -218,11 +180,9 @@ impl<'a> CanvasData<'a> { return; // Paint nothing if gradient size is zero. } - self.drawtarget.fill( - &self.path_builder.finish(), - self.state.fill_style.to_pattern_ref(), - &self.state.draw_options, - ); + self.drawtarget.fill(&self.path_builder.finish(), + self.state.fill_style.to_pattern_ref(), + &self.state.draw_options); } pub fn stroke(&self) { @@ -230,12 +190,10 @@ impl<'a> CanvasData<'a> { return; // Paint nothing if gradient size is zero. } - self.drawtarget.stroke( - &self.path_builder.finish(), - self.state.stroke_style.to_pattern_ref(), - &self.state.stroke_opts, - &self.state.draw_options, - ); + self.drawtarget.stroke(&self.path_builder.finish(), + self.state.stroke_style.to_pattern_ref(), + &self.state.stroke_opts, + &self.state.draw_options); } pub fn clip(&self) { @@ -247,7 +205,7 @@ impl<'a> CanvasData<'a> { x: f64, y: f64, _fill_rule: FillRule, - chan: IpcSender, + chan: IpcSender ) { let path = self.path_builder.finish(); let result = path.contains_point(x, y, &self.state.transform); @@ -264,22 +222,19 @@ impl<'a> CanvasData<'a> { } pub fn rect(&self, rect: &Rect) { - self.path_builder - .move_to(Point2D::new(rect.origin.x, rect.origin.y)); - self.path_builder - .line_to(Point2D::new(rect.origin.x + rect.size.width, rect.origin.y)); - self.path_builder.line_to(Point2D::new( - rect.origin.x + rect.size.width, - rect.origin.y + rect.size.height, - )); - self.path_builder.line_to(Point2D::new( - rect.origin.x, - rect.origin.y + rect.size.height, - )); + self.path_builder.move_to(Point2D::new(rect.origin.x, rect.origin.y)); + self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width, rect.origin.y)); + self.path_builder.line_to(Point2D::new(rect.origin.x + rect.size.width, + rect.origin.y + rect.size.height)); + self.path_builder.line_to(Point2D::new(rect.origin.x, rect.origin.y + rect.size.height)); self.path_builder.close(); } - pub fn quadratic_curve_to(&self, cp: &Point2D, endpoint: &Point2D) { + pub fn quadratic_curve_to( + &self, + cp: &Point2D, + endpoint: &Point2D + ) { self.path_builder.quadratic_curve_to(cp, endpoint) } @@ -287,7 +242,7 @@ impl<'a> CanvasData<'a> { &self, cp1: &Point2D, cp2: &Point2D, - endpoint: &Point2D, + endpoint: &Point2D ) { self.path_builder.bezier_curve_to(cp1, cp2, endpoint) } @@ -298,13 +253,17 @@ impl<'a> CanvasData<'a> { radius: AzFloat, start_angle: AzFloat, end_angle: AzFloat, - ccw: bool, + ccw: bool ) { - self.path_builder - .arc(*center, radius, start_angle, end_angle, ccw) + self.path_builder.arc(*center, radius, start_angle, end_angle, ccw) } - pub fn arc_to(&self, cp1: &Point2D, cp2: &Point2D, radius: AzFloat) { + pub fn arc_to( + &self, + cp1: &Point2D, + cp2: &Point2D, + radius: AzFloat + ) { let cp0 = self.path_builder.get_current_point(); let cp1 = *cp1; let cp2 = *cp2; @@ -350,17 +309,9 @@ impl<'a> CanvasData<'a> { let angle_end = (tp2.y - cy).atan2(tp2.x - cx); self.line_to(&tp1); - if [cx, cy, angle_start, angle_end] - .iter() - .all(|x| x.is_finite()) - { - self.arc( - &Point2D::new(cx, cy), - radius, - angle_start, - angle_end, - anticlockwise, - ); + if [cx, cy, angle_start, angle_end].iter().all(|x| x.is_finite()) { + self.arc(&Point2D::new(cx, cy), radius, + angle_start, angle_end, anticlockwise); } } @@ -372,17 +323,9 @@ impl<'a> CanvasData<'a> { rotation_angle: AzFloat, start_angle: AzFloat, end_angle: AzFloat, - ccw: bool, + ccw: bool ) { - self.path_builder.ellipse( - *center, - radius_x, - radius_y, - rotation_angle, - start_angle, - end_angle, - ccw, - ); + self.path_builder.ellipse(*center, radius_x, radius_y, rotation_angle, start_angle, end_angle, ccw); } pub fn set_fill_style(&mut self, style: FillOrStrokeStyle) { @@ -423,17 +366,14 @@ impl<'a> CanvasData<'a> { } pub fn set_global_composition(&mut self, op: CompositionOrBlending) { - self.state - .draw_options - .set_composition_op(op.to_azure_style()); + self.state.draw_options.set_composition_op(op.to_azure_style()); } - pub fn create(size: Size2D) -> DrawTarget { - // FIXME(nox): Why is the size made of i32 values? - DrawTarget::new(BackendType::Skia, size.to_i32(), SurfaceFormat::B8G8R8A8) + pub fn create(size: Size2D) -> DrawTarget { + DrawTarget::new(BackendType::Skia, size, SurfaceFormat::B8G8R8A8) } - pub fn recreate(&mut self, size: Size2D) { + pub fn recreate(&mut self, size: Size2D) { self.drawtarget = CanvasData::create(size); self.state = CanvasPaintState::new(self.state.draw_options.antialias); self.saved_states.clear(); @@ -452,13 +392,7 @@ impl<'a> CanvasData<'a> { #[allow(unsafe_code)] pub fn send_pixels(&mut self, chan: IpcSender>) { - let data = unsafe { - self.drawtarget - .snapshot() - .get_data_surface() - .data() - .to_vec() - }; + let data = unsafe { self.drawtarget.snapshot().get_data_surface().data().to_vec() }; chan.send(Some(data.into())).unwrap(); } @@ -474,9 +408,9 @@ impl<'a> CanvasData<'a> { is_opaque: false, allow_mipmaps: false, }; - let data = webrender_api::ImageData::Raw(Arc::new(unsafe { - self.drawtarget.snapshot().get_data_surface().data().into() - })); + let data = webrender_api::ImageData::Raw(Arc::new( + unsafe { self.drawtarget.snapshot().get_data_surface().data().into() }, + )); let mut txn = webrender_api::Transaction::new(); @@ -484,17 +418,15 @@ impl<'a> CanvasData<'a> { Some(image_key) => { debug!("Updating image {:?}.", image_key); txn.update_image(image_key, descriptor, data, None); - }, + } None => { self.image_key = Some(self.webrender_api.generate_image_key()); debug!("New image {:?}.", self.image_key); txn.add_image(self.image_key.unwrap(), descriptor, data, None); - }, + } } - if let Some(image_key) = - mem::replace(&mut self.very_old_image_key, self.old_image_key.take()) - { + if let Some(image_key) = mem::replace(&mut self.very_old_image_key, self.old_image_key.take()) { txn.delete_image(image_key); } @@ -506,25 +438,104 @@ impl<'a> CanvasData<'a> { chan.send(data).unwrap(); } + pub fn image_data( + &self, + dest_rect: Rect, + canvas_size: Size2D, + sender: IpcBytesSender, + ) { + sender.send(&self.read_pixels(dest_rect, canvas_size)).unwrap(); + } + // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata - pub fn put_image_data(&mut self, mut imagedata: Vec, rect: Rect) { - assert_eq!(imagedata.len() % 4, 0); - assert_eq!(rect.size.area() as usize, imagedata.len() / 4); - pixels::byte_swap_and_premultiply_inplace(&mut imagedata); - let source_surface = self - .drawtarget - .create_source_surface_from_data( - &imagedata, - rect.size.to_i32(), - rect.size.width as i32 * 4, - SurfaceFormat::B8G8R8A8, - ) - .unwrap(); - self.drawtarget.copy_surface( - source_surface, - Rect::from_size(rect.size.to_i32()), - rect.origin.to_i32(), - ); + pub fn put_image_data( + &mut self, + imagedata: Vec, + offset: Vector2D, + image_data_size: Size2D, + mut dirty_rect: Rect + ) { + if image_data_size.width <= 0.0 || image_data_size.height <= 0.0 { + return + } + + assert_eq!(image_data_size.width * image_data_size.height * 4.0, imagedata.len() as f64); + + // Step 1. TODO (neutered data) + + // Step 2. + if dirty_rect.size.width < 0.0f64 { + dirty_rect.origin.x += dirty_rect.size.width; + dirty_rect.size.width = -dirty_rect.size.width; + } + + if dirty_rect.size.height < 0.0f64 { + dirty_rect.origin.y += dirty_rect.size.height; + dirty_rect.size.height = -dirty_rect.size.height; + } + + // Step 3. + if dirty_rect.origin.x < 0.0f64 { + dirty_rect.size.width += dirty_rect.origin.x; + dirty_rect.origin.x = 0.0f64; + } + + if dirty_rect.origin.y < 0.0f64 { + dirty_rect.size.height += dirty_rect.origin.y; + dirty_rect.origin.y = 0.0f64; + } + + // Step 4. + if dirty_rect.max_x() > image_data_size.width { + dirty_rect.size.width = image_data_size.width - dirty_rect.origin.x; + } + + if dirty_rect.max_y() > image_data_size.height { + dirty_rect.size.height = image_data_size.height - dirty_rect.origin.y; + } + + // 5) If either dirtyWidth or dirtyHeight is negative or zero, + // stop without affecting any bitmaps + if dirty_rect.size.width <= 0.0 || dirty_rect.size.height <= 0.0 { + return + } + + // Step 6. + let dest_rect = dirty_rect.translate(&offset).to_i32(); + + // azure_hl operates with integers. We need to cast the image size + let image_size = image_data_size.to_i32(); + + let first_pixel = dest_rect.origin - offset.to_i32(); + let mut src_line = (first_pixel.y * (image_size.width * 4) + first_pixel.x * 4) as usize; + + let mut dest = + Vec::with_capacity((dest_rect.size.width * dest_rect.size.height * 4) as usize); + + for _ in 0 .. dest_rect.size.height { + let mut src_offset = src_line; + for _ in 0 .. dest_rect.size.width { + let alpha = imagedata[src_offset + 3] as u16; + // add 127 before dividing for more accurate rounding + let premultiply_channel = |channel: u8| (((channel as u16 * alpha) + 127) / 255) as u8; + dest.push(premultiply_channel(imagedata[src_offset + 2])); + dest.push(premultiply_channel(imagedata[src_offset + 1])); + dest.push(premultiply_channel(imagedata[src_offset + 0])); + dest.push(imagedata[src_offset + 3]); + src_offset += 4; + } + src_line += (image_size.width * 4) as usize; + } + + if let Some(source_surface) = self.drawtarget.create_source_surface_from_data( + &dest, + dest_rect.size, + dest_rect.size.width * 4, + SurfaceFormat::B8G8R8A8) { + self.drawtarget.copy_surface(source_surface, + Rect::new(Point2D::new(0, 0), dest_rect.size), + dest_rect.origin); + } } pub fn set_shadow_offset_x(&mut self, value: f64) { @@ -546,19 +557,15 @@ impl<'a> CanvasData<'a> { // https://html.spec.whatwg.org/multipage/#when-shadows-are-drawn fn need_to_draw_shadow(&self) -> bool { self.state.shadow_color.a != 0.0f32 && - (self.state.shadow_offset_x != 0.0f64 || - self.state.shadow_offset_y != 0.0f64 || - self.state.shadow_blur != 0.0f64) + (self.state.shadow_offset_x != 0.0f64 || + self.state.shadow_offset_y != 0.0f64 || + self.state.shadow_blur != 0.0f64) } fn create_draw_target_for_shadow(&self, source_rect: &Rect) -> DrawTarget { - let draw_target = self.drawtarget.create_similar_draw_target( - &Size2D::new( - source_rect.size.width as i32, - source_rect.size.height as i32, - ), - self.drawtarget.get_format(), - ); + let draw_target = self.drawtarget.create_similar_draw_target(&Size2D::new(source_rect.size.width as i32, + source_rect.size.height as i32), + self.drawtarget.get_format()); let matrix = Transform2D::identity() .pre_translate(-source_rect.origin.to_vector().cast()) .pre_mul(&self.state.transform); @@ -567,47 +574,51 @@ impl<'a> CanvasData<'a> { } fn draw_with_shadow(&self, rect: &Rect, draw_shadow_source: F) - where - F: FnOnce(&DrawTarget), + where F: FnOnce(&DrawTarget) { let shadow_src_rect = self.state.transform.transform_rect(rect); let new_draw_target = self.create_draw_target_for_shadow(&shadow_src_rect); draw_shadow_source(&new_draw_target); - self.drawtarget.draw_surface_with_shadow( - new_draw_target.snapshot(), - &Point2D::new( - shadow_src_rect.origin.x as AzFloat, - shadow_src_rect.origin.y as AzFloat, - ), - &self.state.shadow_color, - &Vector2D::new( - self.state.shadow_offset_x as AzFloat, - self.state.shadow_offset_y as AzFloat, - ), - (self.state.shadow_blur / 2.0f64) as AzFloat, - self.state.draw_options.composition, - ); + self.drawtarget.draw_surface_with_shadow(new_draw_target.snapshot(), + &Point2D::new(shadow_src_rect.origin.x as AzFloat, + shadow_src_rect.origin.y as AzFloat), + &self.state.shadow_color, + &Vector2D::new(self.state.shadow_offset_x as AzFloat, + self.state.shadow_offset_y as AzFloat), + (self.state.shadow_blur / 2.0f64) as AzFloat, + self.state.draw_options.composition); } /// It reads image data from the canvas /// canvas_size: The size of the canvas we're reading from /// read_rect: The area of the canvas we want to read from #[allow(unsafe_code)] - pub fn read_pixels(&self, read_rect: Rect, canvas_size: Size2D) -> Vec { - let canvas_rect = Rect::from_size(canvas_size); - if canvas_rect - .intersection(&read_rect) - .map_or(true, |rect| rect.is_empty()) - { - return vec![]; + pub fn read_pixels(&self, read_rect: Rect, canvas_size: Size2D) -> Vec { + let canvas_size = canvas_size.to_i32(); + let canvas_rect = Rect::new(Point2D::new(0i32, 0i32), canvas_size); + let src_read_rect = canvas_rect.intersection(&read_rect).unwrap_or(Rect::zero()); + + if src_read_rect.is_empty() || canvas_size.width <= 0 && canvas_size.height <= 0 { + return vec![]; } + let data_surface = self.drawtarget.snapshot().get_data_surface(); - pixels::get_rect( - unsafe { data_surface.data() }, - canvas_size.to_u32(), - read_rect.to_u32(), - ) - .into_owned() + let src_data = unsafe { data_surface.data() }; + let stride = data_surface.stride(); + + //start offset of the copyable rectangle + let mut src = (src_read_rect.origin.y * stride + src_read_rect.origin.x * 4) as usize; + let mut image_data = Vec::with_capacity( + (src_read_rect.size.width * src_read_rect.size.height * 4) as usize, + ); + //copy the data to the destination vector + for _ in 0..src_read_rect.size.height { + let row = &src_data[src .. src + (4 * src_read_rect.size.width) as usize]; + image_data.extend_from_slice(row); + src += stride as usize; + } + + image_data } } @@ -646,13 +657,7 @@ impl<'a> CanvasPaintState<'a> { draw_options: DrawOptions::new(1.0, CompositionOp::Over, antialias), fill_style: Pattern::Color(ColorPattern::new(Color::black())), stroke_style: Pattern::Color(ColorPattern::new(Color::black())), - stroke_opts: StrokeOptions::new( - 1.0, - JoinStyle::MiterOrBevel, - CapStyle::Butt, - 10.0, - &[], - ), + stroke_opts: StrokeOptions::new(1.0, JoinStyle::MiterOrBevel, CapStyle::Butt, 10.0, &[]), transform: Transform2D::identity(), shadow_offset_x: 0.0, shadow_offset_y: 0.0, @@ -671,6 +676,39 @@ fn is_zero_size_gradient(pattern: &Pattern) -> bool { false } +/// Used by drawImage to get rid of the extra pixels of the image data that +/// won't be copied to the canvas +/// image_data: Color pixel data of the image +/// image_size: Image dimensions +/// crop_rect: It determines the area of the image we want to keep +fn crop_image( + image_data: Vec, + image_size: Size2D, + crop_rect: Rect +) -> Vec { + // We're going to iterate over a pixel values array so we need integers + let crop_rect = crop_rect.to_i32(); + let image_size = image_size.to_i32(); + // Assuming 4 bytes per pixel and row-major order for storage + // (consecutive elements in a pixel row of the image are contiguous in memory) + let stride = image_size.width * 4; + let image_bytes_length = image_size.height * image_size.width * 4; + let crop_area_bytes_length = crop_rect.size.height * crop_rect.size.width * 4; + // If the image size is less or equal than the crop area we do nothing + if image_bytes_length <= crop_area_bytes_length { + return image_data; + } + + let mut new_image_data = Vec::new(); + let mut src = (crop_rect.origin.y * stride + crop_rect.origin.x * 4) as usize; + for _ in 0..crop_rect.size.height { + let row = &image_data[src .. src + (4 * crop_rect.size.width) as usize]; + new_image_data.extend_from_slice(row); + src += stride as usize; + } + new_image_data +} + /// It writes an image to the destination target /// draw_target: the destination target where the image_data will be copied /// image_data: Pixel information of the image to be written. It takes RGBA8 @@ -684,10 +722,10 @@ fn write_image( dest_rect: Rect, smoothing_enabled: bool, composition_op: CompositionOp, - global_alpha: f32, + global_alpha: f32 ) { if image_data.is_empty() { - return; + return } let image_rect = Rect::new(Point2D::zero(), image_size); @@ -700,25 +738,23 @@ fn write_image( } else { Filter::Point }; + // azure_hl operates with integers. We need to cast the image size let image_size = image_size.to_i32(); - let source_surface = draw_target - .create_source_surface_from_data( - &image_data, - image_size, - image_size.width * 4, - SurfaceFormat::B8G8R8A8, - ) - .unwrap(); - let draw_surface_options = DrawSurfaceOptions::new(filter, true); - let draw_options = DrawOptions::new(global_alpha, composition_op, AntialiasMode::None); - draw_target.draw_surface( - source_surface, - dest_rect.to_azure_style(), - image_rect.to_azure_style(), - draw_surface_options, - draw_options, - ); + if let Some(source_surface) = + draw_target.create_source_surface_from_data(&image_data, + image_size, + image_size.width * 4, + SurfaceFormat::B8G8R8A8) { + let draw_surface_options = DrawSurfaceOptions::new(filter, true); + let draw_options = DrawOptions::new(global_alpha, composition_op, AntialiasMode::None); + + draw_target.draw_surface(source_surface, + dest_rect.to_azure_style(), + image_rect.to_azure_style(), + draw_surface_options, + draw_options); + } } pub trait PointToi32 { @@ -727,7 +763,8 @@ pub trait PointToi32 { impl PointToi32 for Point2D { fn to_i32(&self) -> Point2D { - Point2D::new(self.x.to_i32().unwrap(), self.y.to_i32().unwrap()) + Point2D::new(self.x.to_i32().unwrap(), + self.y.to_i32().unwrap()) } } @@ -737,7 +774,8 @@ pub trait SizeToi32 { impl SizeToi32 for Size2D { fn to_i32(&self) -> Size2D { - Size2D::new(self.width.to_i32().unwrap(), self.height.to_i32().unwrap()) + Size2D::new(self.width.to_i32().unwrap(), + self.height.to_i32().unwrap()) } } @@ -748,24 +786,19 @@ pub trait RectToi32 { impl RectToi32 for Rect { fn to_i32(&self) -> Rect { - Rect::new( - Point2D::new( - self.origin.x.to_i32().unwrap(), - self.origin.y.to_i32().unwrap(), - ), - Size2D::new( - self.size.width.to_i32().unwrap(), - self.size.height.to_i32().unwrap(), - ), - ) + Rect::new(Point2D::new(self.origin.x.to_i32().unwrap(), + self.origin.y.to_i32().unwrap()), + Size2D::new(self.size.width.to_i32().unwrap(), + self.size.height.to_i32().unwrap())) } fn ceil(&self) -> Rect { - Rect::new( - Point2D::new(self.origin.x.ceil(), self.origin.y.ceil()), - Size2D::new(self.size.width.ceil(), self.size.height.ceil()), - ) + Rect::new(Point2D::new(self.origin.x.ceil(), + self.origin.y.ceil()), + Size2D::new(self.size.width.ceil(), + self.size.height.ceil())) } + } pub trait ToAzureStyle { @@ -777,13 +810,12 @@ impl ToAzureStyle for Rect { type Target = Rect; fn to_azure_style(self) -> Rect { - Rect::new( - Point2D::new(self.origin.x as AzFloat, self.origin.y as AzFloat), - Size2D::new(self.size.width as AzFloat, self.size.height as AzFloat), - ) + Rect::new(Point2D::new(self.origin.x as AzFloat, self.origin.y as AzFloat), + Size2D::new(self.size.width as AzFloat, self.size.height as AzFloat)) } } + impl ToAzureStyle for LineCapStyle { type Target = CapStyle; @@ -813,17 +845,17 @@ impl ToAzureStyle for CompositionStyle { fn to_azure_style(self) -> CompositionOp { match self { - CompositionStyle::SrcIn => CompositionOp::In, - CompositionStyle::SrcOut => CompositionOp::Out, - CompositionStyle::SrcOver => CompositionOp::Over, - CompositionStyle::SrcAtop => CompositionOp::Atop, - CompositionStyle::DestIn => CompositionOp::DestIn, - CompositionStyle::DestOut => CompositionOp::DestOut, + CompositionStyle::SrcIn => CompositionOp::In, + CompositionStyle::SrcOut => CompositionOp::Out, + CompositionStyle::SrcOver => CompositionOp::Over, + CompositionStyle::SrcAtop => CompositionOp::Atop, + CompositionStyle::DestIn => CompositionOp::DestIn, + CompositionStyle::DestOut => CompositionOp::DestOut, CompositionStyle::DestOver => CompositionOp::DestOver, CompositionStyle::DestAtop => CompositionOp::DestAtop, - CompositionStyle::Copy => CompositionOp::Source, - CompositionStyle::Lighter => CompositionOp::Add, - CompositionStyle::Xor => CompositionOp::Xor, + CompositionStyle::Copy => CompositionOp::Source, + CompositionStyle::Lighter => CompositionOp::Add, + CompositionStyle::Xor => CompositionOp::Xor, } } } @@ -833,20 +865,20 @@ impl ToAzureStyle for BlendingStyle { fn to_azure_style(self) -> CompositionOp { match self { - BlendingStyle::Multiply => CompositionOp::Multiply, - BlendingStyle::Screen => CompositionOp::Screen, - BlendingStyle::Overlay => CompositionOp::Overlay, - BlendingStyle::Darken => CompositionOp::Darken, - BlendingStyle::Lighten => CompositionOp::Lighten, + BlendingStyle::Multiply => CompositionOp::Multiply, + BlendingStyle::Screen => CompositionOp::Screen, + BlendingStyle::Overlay => CompositionOp::Overlay, + BlendingStyle::Darken => CompositionOp::Darken, + BlendingStyle::Lighten => CompositionOp::Lighten, BlendingStyle::ColorDodge => CompositionOp::ColorDodge, - BlendingStyle::ColorBurn => CompositionOp::ColorBurn, - BlendingStyle::HardLight => CompositionOp::HardLight, - BlendingStyle::SoftLight => CompositionOp::SoftLight, + BlendingStyle::ColorBurn => CompositionOp::ColorBurn, + BlendingStyle::HardLight => CompositionOp::HardLight, + BlendingStyle::SoftLight => CompositionOp::SoftLight, BlendingStyle::Difference => CompositionOp::Difference, - BlendingStyle::Exclusion => CompositionOp::Exclusion, - BlendingStyle::Hue => CompositionOp::Hue, + BlendingStyle::Exclusion => CompositionOp::Exclusion, + BlendingStyle::Hue => CompositionOp::Hue, BlendingStyle::Saturation => CompositionOp::Saturation, - BlendingStyle::Color => CompositionOp::Color, + BlendingStyle::Color => CompositionOp::Color, BlendingStyle::Luminosity => CompositionOp::Luminosity, } } @@ -869,74 +901,53 @@ pub trait ToAzurePattern { impl ToAzurePattern for FillOrStrokeStyle { fn to_azure_pattern(&self, drawtarget: &DrawTarget) -> Option { - Some(match *self { + match *self { FillOrStrokeStyle::Color(ref color) => { - Pattern::Color(ColorPattern::new(color.to_azure_style())) + Some(Pattern::Color(ColorPattern::new(color.to_azure_style()))) }, FillOrStrokeStyle::LinearGradient(ref linear_gradient_style) => { - let gradient_stops: Vec = linear_gradient_style - .stops - .iter() - .map(|s| GradientStop { + let gradient_stops: Vec = linear_gradient_style.stops.iter().map(|s| { + GradientStop { offset: s.offset as AzFloat, - color: s.color.to_azure_style(), - }) - .collect(); - - Pattern::LinearGradient(LinearGradientPattern::new( - &Point2D::new( - linear_gradient_style.x0 as AzFloat, - linear_gradient_style.y0 as AzFloat, - ), - &Point2D::new( - linear_gradient_style.x1 as AzFloat, - linear_gradient_style.y1 as AzFloat, - ), + color: s.color.to_azure_style() + } + }).collect(); + + Some(Pattern::LinearGradient(LinearGradientPattern::new( + &Point2D::new(linear_gradient_style.x0 as AzFloat, linear_gradient_style.y0 as AzFloat), + &Point2D::new(linear_gradient_style.x1 as AzFloat, linear_gradient_style.y1 as AzFloat), drawtarget.create_gradient_stops(&gradient_stops, ExtendMode::Clamp), - &Transform2D::identity(), - )) + &Transform2D::identity()))) }, FillOrStrokeStyle::RadialGradient(ref radial_gradient_style) => { - let gradient_stops: Vec = radial_gradient_style - .stops - .iter() - .map(|s| GradientStop { + let gradient_stops: Vec = radial_gradient_style.stops.iter().map(|s| { + GradientStop { offset: s.offset as AzFloat, - color: s.color.to_azure_style(), - }) - .collect(); - - Pattern::RadialGradient(RadialGradientPattern::new( - &Point2D::new( - radial_gradient_style.x0 as AzFloat, - radial_gradient_style.y0 as AzFloat, - ), - &Point2D::new( - radial_gradient_style.x1 as AzFloat, - radial_gradient_style.y1 as AzFloat, - ), - radial_gradient_style.r0 as AzFloat, - radial_gradient_style.r1 as AzFloat, + color: s.color.to_azure_style() + } + }).collect(); + + Some(Pattern::RadialGradient(RadialGradientPattern::new( + &Point2D::new(radial_gradient_style.x0 as AzFloat, radial_gradient_style.y0 as AzFloat), + &Point2D::new(radial_gradient_style.x1 as AzFloat, radial_gradient_style.y1 as AzFloat), + radial_gradient_style.r0 as AzFloat, radial_gradient_style.r1 as AzFloat, drawtarget.create_gradient_stops(&gradient_stops, ExtendMode::Clamp), - &Transform2D::identity(), - )) + &Transform2D::identity()))) }, FillOrStrokeStyle::Surface(ref surface_style) => { - let source_surface = drawtarget.create_source_surface_from_data( - &surface_style.surface_data, - // FIXME(nox): Why are those i32 values? - surface_style.surface_size.to_i32(), - surface_style.surface_size.width as i32 * 4, - SurfaceFormat::B8G8R8A8, - )?; - Pattern::Surface(SurfacePattern::new( - source_surface.azure_source_surface, - surface_style.repeat_x, - surface_style.repeat_y, - &Transform2D::identity(), - )) - }, - }) + drawtarget.create_source_surface_from_data(&surface_style.surface_data, + surface_style.surface_size, + surface_style.surface_size.width * 4, + SurfaceFormat::B8G8R8A8) + .map(|source_surface| { + Pattern::Surface(SurfacePattern::new( + source_surface.azure_source_surface, + surface_style.repeat_x, + surface_style.repeat_y, + &Transform2D::identity())) + }) + } + } } } @@ -944,11 +955,9 @@ impl ToAzureStyle for RGBA { type Target = Color; fn to_azure_style(self) -> Color { - Color::rgba( - self.red_f32() as AzFloat, - self.green_f32() as AzFloat, - self.blue_f32() as AzFloat, - self.alpha_f32() as AzFloat, - ) + Color::rgba(self.red_f32() as AzFloat, + self.green_f32() as AzFloat, + self.blue_f32() as AzFloat, + self.alpha_f32() as AzFloat) } } diff --git a/components/canvas/canvas_paint_thread.rs b/components/canvas/canvas_paint_thread.rs index d4f00506a3e5..3e66194e94ca 100644 --- a/components/canvas/canvas_paint_thread.rs +++ b/components/canvas/canvas_paint_thread.rs @@ -3,21 +3,22 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use azure::azure_hl::AntialiasMode; +use canvas_data::*; use canvas_traits::canvas::*; -use crate::canvas_data::*; use euclid::Size2D; use ipc_channel::ipc::{self, IpcSender}; use std::borrow::ToOwned; use std::collections::HashMap; use std::thread; +use webrender_api; -pub struct CanvasPaintThread<'a> { +pub struct CanvasPaintThread <'a> { canvases: HashMap>, next_canvas_id: CanvasId, } -impl<'a> CanvasPaintThread<'a> { - fn new() -> CanvasPaintThread<'a> { +impl<'a> CanvasPaintThread <'a> { + fn new() -> CanvasPaintThread <'a> { CanvasPaintThread { canvases: HashMap::new(), next_canvas_id: CanvasId(0), @@ -28,58 +29,60 @@ impl<'a> CanvasPaintThread<'a> { /// communicate with it. pub fn start() -> IpcSender { let (sender, receiver) = ipc::channel::().unwrap(); - thread::Builder::new() - .name("CanvasThread".to_owned()) - .spawn(move || { - let mut canvas_paint_thread = CanvasPaintThread::new(); - loop { - match receiver.recv() { - Ok(msg) => match msg { + thread::Builder::new().name("CanvasThread".to_owned()).spawn(move || { + let mut canvas_paint_thread = CanvasPaintThread::new(); + loop { + match receiver.recv() { + Ok(msg) => { + match msg { CanvasMsg::Canvas2d(message, canvas_id) => { canvas_paint_thread.process_canvas_2d_message(message, canvas_id); }, - CanvasMsg::Close(canvas_id) => { + CanvasMsg::Close(canvas_id) =>{ canvas_paint_thread.canvases.remove(&canvas_id); }, CanvasMsg::Create(creator, size, webrenderer_api_sender, antialias) => { let canvas_id = canvas_paint_thread.create_canvas( size, webrenderer_api_sender, - antialias, + antialias ); creator.send(canvas_id).unwrap(); }, - CanvasMsg::Recreate(size, canvas_id) => { + CanvasMsg::Recreate(size, canvas_id) =>{ canvas_paint_thread.canvas(canvas_id).recreate(size); }, - CanvasMsg::FromScript(message, canvas_id) => match message { - FromScriptMsg::SendPixels(chan) => { - canvas_paint_thread.canvas(canvas_id).send_pixels(chan); - }, + CanvasMsg::FromScript(message, canvas_id) => { + match message { + FromScriptMsg::SendPixels(chan) => { + canvas_paint_thread.canvas(canvas_id).send_pixels(chan); + } + } }, - CanvasMsg::FromLayout(message, canvas_id) => match message { - FromLayoutMsg::SendData(chan) => { - canvas_paint_thread.canvas(canvas_id).send_data(chan); - }, + CanvasMsg::FromLayout(message, canvas_id) => { + match message { + FromLayoutMsg::SendData(chan) => { + canvas_paint_thread.canvas(canvas_id).send_data(chan); + } + } }, - CanvasMsg::Exit => break, - }, - Err(e) => { - warn!("Error on CanvasPaintThread receive ({})", e); - }, + } + }, + Err(e) => { + warn!("Error on CanvasPaintThread receive ({})", e); } } - }) - .expect("Thread spawning failed"); + } + }).expect("Thread spawning failed"); sender } pub fn create_canvas( &mut self, - size: Size2D, + size: Size2D, webrender_api_sender: webrender_api::RenderApiSender, - antialias: bool, + antialias: bool ) -> CanvasId { let antialias = if antialias { AntialiasMode::Default @@ -101,17 +104,33 @@ impl<'a> CanvasPaintThread<'a> { Canvas2dMsg::FillText(text, x, y, max_width) => { self.canvas(canvas_id).fill_text(text, x, y, max_width) }, - Canvas2dMsg::FillRect(ref rect) => self.canvas(canvas_id).fill_rect(rect), - Canvas2dMsg::StrokeRect(ref rect) => self.canvas(canvas_id).stroke_rect(rect), - Canvas2dMsg::ClearRect(ref rect) => self.canvas(canvas_id).clear_rect(rect), - Canvas2dMsg::BeginPath => self.canvas(canvas_id).begin_path(), - Canvas2dMsg::ClosePath => self.canvas(canvas_id).close_path(), - Canvas2dMsg::Fill => self.canvas(canvas_id).fill(), - Canvas2dMsg::Stroke => self.canvas(canvas_id).stroke(), - Canvas2dMsg::Clip => self.canvas(canvas_id).clip(), - Canvas2dMsg::IsPointInPath(x, y, fill_rule, chan) => self - .canvas(canvas_id) - .is_point_in_path(x, y, fill_rule, chan), + Canvas2dMsg::FillRect(ref rect) => { + self.canvas(canvas_id).fill_rect(rect) + }, + Canvas2dMsg::StrokeRect(ref rect) => { + self.canvas(canvas_id).stroke_rect(rect) + }, + Canvas2dMsg::ClearRect(ref rect) => { + self.canvas(canvas_id).clear_rect(rect) + }, + Canvas2dMsg::BeginPath => { + self.canvas(canvas_id).begin_path() + }, + Canvas2dMsg::ClosePath => { + self.canvas(canvas_id).close_path() + }, + Canvas2dMsg::Fill => { + self.canvas(canvas_id).fill() + }, + Canvas2dMsg::Stroke => { + self.canvas(canvas_id).stroke() + }, + Canvas2dMsg::Clip => { + self.canvas(canvas_id).clip() + }, + Canvas2dMsg::IsPointInPath(x, y, fill_rule, chan) => { + self.canvas(canvas_id).is_point_in_path(x, y, fill_rule, chan) + }, Canvas2dMsg::DrawImage( imagedata, image_size, @@ -119,10 +138,13 @@ impl<'a> CanvasPaintThread<'a> { source_rect, smoothing_enabled, ) => { - let data = imagedata.map_or_else( - || vec![0; image_size.width as usize * image_size.height as usize * 4], - |bytes| bytes.into(), - ); + let data = match imagedata { + None => vec![0; image_size.width as usize * image_size.height as usize * 4], + Some(mut data) => { + byte_swap(&mut data); + data.into() + }, + }; self.canvas(canvas_id).draw_image( data, image_size, @@ -136,11 +158,12 @@ impl<'a> CanvasPaintThread<'a> { image_size, dest_rect, source_rect, - smoothing, + smoothing ) => { - let image_data = self - .canvas(canvas_id) - .read_pixels(source_rect.to_u32(), image_size.to_u32()); + let image_data = self.canvas(canvas_id).read_pixels( + source_rect.to_i32(), + image_size, + ); self.canvas(other_canvas_id).draw_image( image_data.into(), source_rect.size, @@ -149,44 +172,86 @@ impl<'a> CanvasPaintThread<'a> { smoothing, ); }, - Canvas2dMsg::MoveTo(ref point) => self.canvas(canvas_id).move_to(point), - Canvas2dMsg::LineTo(ref point) => self.canvas(canvas_id).line_to(point), - Canvas2dMsg::Rect(ref rect) => self.canvas(canvas_id).rect(rect), - Canvas2dMsg::QuadraticCurveTo(ref cp, ref pt) => { - self.canvas(canvas_id).quadratic_curve_to(cp, pt) + Canvas2dMsg::MoveTo(ref point) => { + self.canvas(canvas_id).move_to(point) }, - Canvas2dMsg::BezierCurveTo(ref cp1, ref cp2, ref pt) => { - self.canvas(canvas_id).bezier_curve_to(cp1, cp2, pt) + Canvas2dMsg::LineTo(ref point) => { + self.canvas(canvas_id).line_to(point) }, - Canvas2dMsg::Arc(ref center, radius, start, end, ccw) => { - self.canvas(canvas_id).arc(center, radius, start, end, ccw) + Canvas2dMsg::Rect(ref rect) => { + self.canvas(canvas_id).rect(rect) }, + Canvas2dMsg::QuadraticCurveTo(ref cp, ref pt) => { + self.canvas(canvas_id).quadratic_curve_to(cp, pt) + } + Canvas2dMsg::BezierCurveTo(ref cp1, ref cp2, ref pt) => { + self.canvas(canvas_id).bezier_curve_to(cp1, cp2, pt) + } + Canvas2dMsg::Arc(ref center, radius, start, end, ccw) => { + self.canvas(canvas_id).arc(center, radius, start, end, ccw) + } Canvas2dMsg::ArcTo(ref cp1, ref cp2, radius) => { self.canvas(canvas_id).arc_to(cp1, cp2, radius) + } + Canvas2dMsg::Ellipse(ref center, radius_x, radius_y, rotation, start, end, ccw) => { + self.canvas(canvas_id).ellipse( + center, + radius_x, + radius_y, + rotation, + start, + end, + ccw + ) + } + Canvas2dMsg::RestoreContext => { + self.canvas(canvas_id).restore_context_state() + }, + Canvas2dMsg::SaveContext => { + self.canvas(canvas_id).save_context_state() + }, + Canvas2dMsg::SetFillStyle(style) => { + self.canvas(canvas_id).set_fill_style(style) + }, + Canvas2dMsg::SetStrokeStyle(style) => { + self.canvas(canvas_id).set_stroke_style(style) + }, + Canvas2dMsg::SetLineWidth(width) => { + self.canvas(canvas_id).set_line_width(width) + }, + Canvas2dMsg::SetLineCap(cap) => { + self.canvas(canvas_id).set_line_cap(cap) + }, + Canvas2dMsg::SetLineJoin(join) => { + self.canvas(canvas_id).set_line_join(join) + }, + Canvas2dMsg::SetMiterLimit(limit) => { + self.canvas(canvas_id).set_miter_limit(limit) + }, + Canvas2dMsg::SetTransform(ref matrix) => { + self.canvas(canvas_id).set_transform(matrix) + }, + Canvas2dMsg::SetGlobalAlpha(alpha) => { + self.canvas(canvas_id).set_global_alpha(alpha) }, - Canvas2dMsg::Ellipse(ref center, radius_x, radius_y, rotation, start, end, ccw) => self - .canvas(canvas_id) - .ellipse(center, radius_x, radius_y, rotation, start, end, ccw), - Canvas2dMsg::RestoreContext => self.canvas(canvas_id).restore_context_state(), - Canvas2dMsg::SaveContext => self.canvas(canvas_id).save_context_state(), - Canvas2dMsg::SetFillStyle(style) => self.canvas(canvas_id).set_fill_style(style), - Canvas2dMsg::SetStrokeStyle(style) => self.canvas(canvas_id).set_stroke_style(style), - Canvas2dMsg::SetLineWidth(width) => self.canvas(canvas_id).set_line_width(width), - Canvas2dMsg::SetLineCap(cap) => self.canvas(canvas_id).set_line_cap(cap), - Canvas2dMsg::SetLineJoin(join) => self.canvas(canvas_id).set_line_join(join), - Canvas2dMsg::SetMiterLimit(limit) => self.canvas(canvas_id).set_miter_limit(limit), - Canvas2dMsg::SetTransform(ref matrix) => self.canvas(canvas_id).set_transform(matrix), - Canvas2dMsg::SetGlobalAlpha(alpha) => self.canvas(canvas_id).set_global_alpha(alpha), Canvas2dMsg::SetGlobalComposition(op) => { self.canvas(canvas_id).set_global_composition(op) }, - Canvas2dMsg::GetImageData(dest_rect, canvas_size, sender) => { - let pixels = self.canvas(canvas_id).read_pixels(dest_rect, canvas_size); - sender.send(&pixels).unwrap(); + Canvas2dMsg::GetImageData(dest_rect, canvas_size, chan) => { + self.canvas(canvas_id).image_data(dest_rect, canvas_size, chan) }, - Canvas2dMsg::PutImageData(rect, receiver) => { - self.canvas(canvas_id) - .put_image_data(receiver.recv().unwrap(), rect); + Canvas2dMsg::PutImageData( + imagedata, + offset, + image_data_size, + dirty_rect, + ) => { + self.canvas(canvas_id).put_image_data( + imagedata.into(), + offset, + image_data_size, + dirty_rect, + ) }, Canvas2dMsg::SetShadowOffsetX(value) => { self.canvas(canvas_id).set_shadow_offset_x(value) @@ -194,10 +259,12 @@ impl<'a> CanvasPaintThread<'a> { Canvas2dMsg::SetShadowOffsetY(value) => { self.canvas(canvas_id).set_shadow_offset_y(value) }, - Canvas2dMsg::SetShadowBlur(value) => self.canvas(canvas_id).set_shadow_blur(value), - Canvas2dMsg::SetShadowColor(ref color) => self - .canvas(canvas_id) - .set_shadow_color(color.to_azure_style()), + Canvas2dMsg::SetShadowBlur(value) => { + self.canvas(canvas_id).set_shadow_blur(value) + }, + Canvas2dMsg::SetShadowColor(ref color) => { + self.canvas(canvas_id).set_shadow_color(color.to_azure_style()) + }, } } diff --git a/components/canvas/gl_context.rs b/components/canvas/gl_context.rs index 9f8aeb2fe31f..c90ecec9ccab 100644 --- a/components/canvas/gl_context.rs +++ b/components/canvas/gl_context.rs @@ -2,18 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::webgl_thread::{GLState, WebGLImpl}; -use canvas_traits::webgl::{WebGLCommand, WebGLCommandBacktrace, WebGLVersion}; -use compositing::compositor_thread::{self, CompositorProxy}; +use canvas_traits::webgl::{WebGLCommand, WebGLVersion, WebGLCommandBacktrace}; +use compositing::compositor_thread::{CompositorProxy, self}; use euclid::Size2D; use gleam::gl; -use offscreen_gl_context::{ - ColorAttachmentType, GLContext, GLContextAttributes, GLContextDispatcher, -}; +use offscreen_gl_context::{ColorAttachmentType, GLContext, GLContextAttributes, GLContextDispatcher}; use offscreen_gl_context::{GLLimits, GLVersion}; use offscreen_gl_context::{NativeGLContext, NativeGLContextHandle, NativeGLContextMethods}; use offscreen_gl_context::{OSMesaContext, OSMesaContextHandle}; use std::sync::{Arc, Mutex}; +use super::webgl_thread::{WebGLImpl, GLState}; /// The GLContextFactory is used to create shared GL contexts with the main thread GL context. /// Currently, shared textures are used to render WebGL textures into the WR compositor. @@ -49,71 +47,63 @@ impl GLContextFactory { pub fn new_shared_context( &self, webgl_version: WebGLVersion, - size: Size2D, - attributes: GLContextAttributes, + size: Size2D, + attributes: GLContextAttributes ) -> Result { - Ok(match *self { + match *self { GLContextFactory::Native(ref handle, ref dispatcher) => { let dispatcher = dispatcher.as_ref().map(|d| Box::new(d.clone()) as Box<_>); - GLContextWrapper::Native(GLContext::new_shared_with_dispatcher( - // FIXME(nox): Why are those i32 values? - size.to_i32(), - attributes, - ColorAttachmentType::Texture, - gl::GlType::default(), - Self::gl_version(webgl_version), - Some(handle), - dispatcher, - )?) - }, + let ctx = GLContext::::new_shared_with_dispatcher(size, + attributes, + ColorAttachmentType::Texture, + gl::GlType::default(), + Self::gl_version(webgl_version), + Some(handle), + dispatcher); + ctx.map(GLContextWrapper::Native) + } GLContextFactory::OSMesa(ref handle) => { - GLContextWrapper::OSMesa(GLContext::new_shared_with_dispatcher( - // FIXME(nox): Why are those i32 values? - size.to_i32(), - attributes, - ColorAttachmentType::Texture, - gl::GlType::default(), - Self::gl_version(webgl_version), - Some(handle), - None, - )?) - }, - }) + let ctx = GLContext::::new_shared_with_dispatcher(size.to_untyped(), + attributes, + ColorAttachmentType::Texture, + gl::GlType::default(), + Self::gl_version(webgl_version), + Some(handle), + None); + ctx.map(GLContextWrapper::OSMesa) + } + } } /// Creates a new non-shared GLContext pub fn new_context( &self, webgl_version: WebGLVersion, - size: Size2D, - attributes: GLContextAttributes, + size: Size2D, + attributes: GLContextAttributes ) -> Result { - Ok(match *self { + match *self { GLContextFactory::Native(..) => { - GLContextWrapper::Native(GLContext::new_shared_with_dispatcher( - // FIXME(nox): Why are those i32 values? - size.to_i32(), - attributes, - ColorAttachmentType::Texture, - gl::GlType::default(), - Self::gl_version(webgl_version), - None, - None, - )?) - }, + let ctx = GLContext::::new_shared_with_dispatcher(size, + attributes, + ColorAttachmentType::Texture, + gl::GlType::default(), + Self::gl_version(webgl_version), + None, + None); + ctx.map(GLContextWrapper::Native) + } GLContextFactory::OSMesa(_) => { - GLContextWrapper::OSMesa(GLContext::new_shared_with_dispatcher( - // FIXME(nox): Why are those i32 values? - size.to_i32(), - attributes, - ColorAttachmentType::Texture, - gl::GlType::default(), - Self::gl_version(webgl_version), - None, - None, - )?) - }, - }) + let ctx = GLContext::::new_shared_with_dispatcher(size.to_untyped(), + attributes, + ColorAttachmentType::Texture, + gl::GlType::default(), + Self::gl_version(webgl_version), + None, + None); + ctx.map(GLContextWrapper::OSMesa) + } + } } fn gl_version(webgl_version: WebGLVersion) -> GLVersion { @@ -124,6 +114,7 @@ impl GLContextFactory { } } + /// GLContextWrapper used to abstract NativeGLContext and OSMesaContext types pub enum GLContextWrapper { Native(GLContext), @@ -135,10 +126,10 @@ impl GLContextWrapper { match *self { GLContextWrapper::Native(ref ctx) => { ctx.make_current().unwrap(); - }, + } GLContextWrapper::OSMesa(ref ctx) => { ctx.make_current().unwrap(); - }, + } } } @@ -146,10 +137,10 @@ impl GLContextWrapper { match *self { GLContextWrapper::Native(ref ctx) => { ctx.unbind().unwrap(); - }, + } GLContextWrapper::OSMesa(ref ctx) => { ctx.unbind().unwrap(); - }, + } } } @@ -157,22 +148,26 @@ impl GLContextWrapper { &self, cmd: WebGLCommand, backtrace: WebGLCommandBacktrace, - state: &mut GLState, + state: &mut GLState ) { match *self { GLContextWrapper::Native(ref ctx) => { WebGLImpl::apply(ctx, state, cmd, backtrace); - }, + } GLContextWrapper::OSMesa(ref ctx) => { WebGLImpl::apply(ctx, state, cmd, backtrace); - }, + } } } - pub fn gl(&self) -> &dyn gl::Gl { + pub fn gl(&self) -> &gl::Gl { match *self { - GLContextWrapper::Native(ref ctx) => ctx.gl(), - GLContextWrapper::OSMesa(ref ctx) => ctx.gl(), + GLContextWrapper::Native(ref ctx) => { + ctx.gl() + } + GLContextWrapper::OSMesa(ref ctx) => { + ctx.gl() + } } } @@ -181,42 +176,34 @@ impl GLContextWrapper { GLContextWrapper::Native(ref ctx) => { let (real_size, texture_id) = { let draw_buffer = ctx.borrow_draw_buffer().unwrap(); - ( - draw_buffer.size(), - draw_buffer.get_bound_texture_id().unwrap(), - ) + (draw_buffer.size(), draw_buffer.get_bound_texture_id().unwrap()) }; let limits = ctx.borrow_limits().clone(); (real_size, texture_id, limits) - }, + } GLContextWrapper::OSMesa(ref ctx) => { let (real_size, texture_id) = { let draw_buffer = ctx.borrow_draw_buffer().unwrap(); - ( - draw_buffer.size(), - draw_buffer.get_bound_texture_id().unwrap(), - ) + (draw_buffer.size(), draw_buffer.get_bound_texture_id().unwrap()) }; let limits = ctx.borrow_limits().clone(); (real_size, texture_id, limits) - }, + } } } - pub fn resize(&mut self, size: Size2D) -> Result<(), &'static str> { + pub fn resize(&mut self, size: Size2D) -> Result<(), &'static str> { match *self { GLContextWrapper::Native(ref mut ctx) => { - // FIXME(nox): Why are those i32 values? - ctx.resize(size.to_i32()) - }, + ctx.resize(size) + } GLContextWrapper::OSMesa(ref mut ctx) => { - // FIXME(nox): Why are those i32 values? - ctx.resize(size.to_i32()) - }, + ctx.resize(size) + } } } } @@ -225,7 +212,7 @@ impl GLContextWrapper { /// It's used in Windows to allow WGL GLContext sharing. #[derive(Clone)] pub struct MainThreadDispatcher { - compositor_proxy: Arc>, + compositor_proxy: Arc> } impl MainThreadDispatcher { @@ -236,10 +223,7 @@ impl MainThreadDispatcher { } } impl GLContextDispatcher for MainThreadDispatcher { - fn dispatch(&self, f: Box) { - self.compositor_proxy - .lock() - .unwrap() - .send(compositor_thread::Msg::Dispatch(f)); + fn dispatch(&self, f: Box) { + self.compositor_proxy.lock().unwrap().send(compositor_thread::Msg::Dispatch(f)); } } diff --git a/components/canvas/lib.rs b/components/canvas/lib.rs index ab785a5620cf..8da9544de6ee 100644 --- a/components/canvas/lib.rs +++ b/components/canvas/lib.rs @@ -4,8 +4,21 @@ #![deny(unsafe_code)] -#[macro_use] -extern crate log; +extern crate azure; +extern crate canvas_traits; +extern crate compositing; +extern crate cssparser; +extern crate euclid; +extern crate fnv; +extern crate gleam; +extern crate ipc_channel; +#[macro_use] extern crate log; +extern crate num_traits; +extern crate offscreen_gl_context; +extern crate serde_bytes; +extern crate servo_config; +extern crate webrender; +extern crate webrender_api; pub mod canvas_data; pub mod canvas_paint_thread; diff --git a/components/canvas/webgl_mode/inprocess.rs b/components/canvas/webgl_mode/inprocess.rs index 8200d4dde3ed..51337f666995 100644 --- a/components/canvas/webgl_mode/inprocess.rs +++ b/components/canvas/webgl_mode/inprocess.rs @@ -2,17 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use canvas_traits::webgl::webgl_channel; -use canvas_traits::webgl::DOMToTextureCommand; +use ::gl_context::GLContextFactory; use canvas_traits::webgl::{WebGLChan, WebGLContextId, WebGLMsg, WebGLPipeline, WebGLReceiver}; use canvas_traits::webgl::{WebGLSender, WebVRCommand, WebVRRenderHandler}; -use crate::gl_context::GLContextFactory; -use crate::webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; +use canvas_traits::webgl::DOMToTextureCommand; +use canvas_traits::webgl::webgl_channel; use euclid::Size2D; use fnv::FnvHashMap; use gleam::gl; use servo_config::prefs::PREFS; use std::rc::Rc; +use webgl_thread::{WebGLExternalImageApi, WebGLExternalImageHandler, WebGLThread}; +use webrender; +use webrender_api; /// WebGL Threading API entry point that lives in the constellation. pub struct WebGLThreads(WebGLSender); @@ -21,13 +23,13 @@ impl WebGLThreads { /// Creates a new WebGLThreads object pub fn new( gl_factory: GLContextFactory, - webrender_gl: Rc, + webrender_gl: Rc, webrender_api_sender: webrender_api::RenderApiSender, - webvr_compositor: Option>, + webvr_compositor: Option>, ) -> ( WebGLThreads, - Box, - Option>, + Box, + Option>, ) { // This implementation creates a single `WebGLThread` for all the pipelines. let channel = WebGLThread::start( @@ -68,7 +70,7 @@ impl WebGLThreads { /// Bridge between the webrender::ExternalImage callbacks and the WebGLThreads. struct WebGLExternalImages { - webrender_gl: Rc, + webrender_gl: Rc, webgl_channel: WebGLSender, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( @@ -78,7 +80,7 @@ struct WebGLExternalImages { } impl WebGLExternalImages { - fn new(webrender_gl: Rc, channel: WebGLSender) -> Self { + fn new(webrender_gl: Rc, channel: WebGLSender) -> Self { Self { webrender_gl, webgl_channel: channel, @@ -109,7 +111,7 @@ impl WebGLExternalImageApi for WebGLExternalImages { } /// Wrapper to send WebVR commands used in `WebGLThread`. -struct WebVRRenderWrapper(Box); +struct WebVRRenderWrapper(Box); impl WebVRRenderHandler for WebVRRenderWrapper { fn handle(&mut self, command: WebVRCommand, texture: Option<(u32, Size2D)>) { @@ -120,7 +122,7 @@ impl WebVRRenderHandler for WebVRRenderWrapper { /// struct used to implement DOMToTexture feature and webrender::OutputImageHandler trait. type OutputHandlerData = Option<(u32, Size2D)>; struct OutputHandler { - webrender_gl: Rc, + webrender_gl: Rc, webgl_channel: WebGLSender, // Used to avoid creating a new channel on each received WebRender request. lock_channel: ( @@ -131,7 +133,7 @@ struct OutputHandler { } impl OutputHandler { - fn new(webrender_gl: Rc, channel: WebGLSender) -> Self { + fn new(webrender_gl: Rc, channel: WebGLSender) -> Self { Self { webrender_gl, webgl_channel: channel, diff --git a/components/canvas/webgl_thread.rs b/components/canvas/webgl_thread.rs index dec2ad332631..4a2466d64e36 100644 --- a/components/canvas/webgl_thread.rs +++ b/components/canvas/webgl_thread.rs @@ -2,17 +2,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::gl_context::{GLContextFactory, GLContextWrapper}; +use canvas_traits::canvas::byte_swap; use canvas_traits::webgl::*; use euclid::Size2D; use fnv::FnvHashMap; use gleam::gl; +use ipc_channel::ipc::IpcBytesSender; use offscreen_gl_context::{GLContext, GLContextAttributes, GLLimits, NativeGLContextMethods}; use std::thread; +use super::gl_context::{GLContextFactory, GLContextWrapper}; +use webrender; +use webrender_api; /// WebGL Threading API entry point that lives in the constellation. /// It allows to get a WebGLThread handle for each script pipeline. -pub use crate::webgl_mode::WebGLThreads; +pub use ::webgl_mode::WebGLThreads; struct GLContextData { ctx: GLContextWrapper, @@ -89,21 +93,21 @@ impl WebGLThread { ) -> WebGLSender { let (sender, receiver) = webgl_channel::().unwrap(); let result = sender.clone(); - thread::Builder::new() - .name("WebGLThread".to_owned()) - .spawn(move || { - let mut renderer = - WebGLThread::new(gl_factory, webrender_api_sender, webvr_compositor); - let webgl_chan = WebGLChan(sender); - loop { - let msg = receiver.recv().unwrap(); - let exit = renderer.handle_msg(msg, &webgl_chan); - if exit { - return; - } + thread::Builder::new().name("WebGLThread".to_owned()).spawn(move || { + let mut renderer = WebGLThread::new( + gl_factory, + webrender_api_sender, + webvr_compositor, + ); + let webgl_chan = WebGLChan(sender); + loop { + let msg = receiver.recv().unwrap(); + let exit = renderer.handle_msg(msg, &webgl_chan); + if exit { + return; } - }) - .expect("Thread spawning failed"); + } + }).expect("Thread spawning failed"); result } @@ -114,32 +118,18 @@ impl WebGLThread { match msg { WebGLMsg::CreateContext(version, size, attributes, result_sender) => { let result = self.create_webgl_context(version, size, attributes); - result_sender - .send(result.map(|(id, limits, share_mode)| { - let data = Self::make_current_if_needed( - id, - &self.contexts, - &mut self.bound_context_id, - ) - .expect("WebGLContext not found"); - let glsl_version = Self::get_glsl_version(&data.ctx); - - // FIXME(nox): Should probably be done by offscreen_gl_context. - if (glsl_version.major, glsl_version.minor) < (3, 1) { - data.ctx.gl().enable(gl::POINT_SPRITE); - } - if !is_gles() { - data.ctx.gl().enable(gl::PROGRAM_POINT_SIZE); - } - - WebGLCreateContextResult { - sender: WebGLMsgSender::new(id, webgl_chan.clone()), - limits, - share_mode, - glsl_version, - } - })) - .unwrap(); + result_sender.send(result.map(|(id, limits, share_mode)| { + let data = Self::make_current_if_needed(id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found"); + let glsl_version = Self::get_glsl_version(&data.ctx); + + WebGLCreateContextResult { + sender: WebGLMsgSender::new(id, webgl_chan.clone()), + limits, + share_mode, + glsl_version, + } + })).unwrap(); }, WebGLMsg::ResizeContext(ctx_id, size, sender) => { self.resize_webgl_context(ctx_id, size, sender); @@ -167,7 +157,7 @@ impl WebGLThread { }, WebGLMsg::Exit => { return true; - }, + } } false @@ -180,11 +170,7 @@ impl WebGLThread { command: WebGLCommand, backtrace: WebGLCommandBacktrace, ) { - let data = Self::make_current_if_needed_mut( - context_id, - &mut self.contexts, - &mut self.bound_context_id, - ); + let data = Self::make_current_if_needed_mut(context_id, &mut self.contexts, &mut self.bound_context_id); if let Some(data) = data { data.ctx.apply_command(command, backtrace, &mut data.state); } @@ -194,24 +180,18 @@ impl WebGLThread { fn handle_webvr_command(&mut self, context_id: WebGLContextId, command: WebVRCommand) { Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id); let texture = match command { - WebVRCommand::SubmitFrame(..) => self.cached_context_info.get(&context_id), - _ => None, + WebVRCommand::SubmitFrame(..) => { + self.cached_context_info.get(&context_id) + }, + _ => None }; - self.webvr_compositor - .as_mut() - .unwrap() - .handle(command, texture.map(|t| (t.texture_id, t.size))); + self.webvr_compositor.as_mut().unwrap().handle(command, texture.map(|t| (t.texture_id, t.size))); } /// Handles a lock external callback received from webrender::ExternalImageHandler - fn handle_lock( - &mut self, - context_id: WebGLContextId, - sender: WebGLSender<(u32, Size2D, usize)>, - ) { - let data = - Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found in a WebGLMsg::Lock message"); + fn handle_lock(&mut self, context_id: WebGLContextId, sender: WebGLSender<(u32, Size2D, usize)>) { + let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found in a WebGLMsg::Lock message"); let info = self.cached_context_info.get_mut(&context_id).unwrap(); // Insert a OpenGL Fence sync object that sends a signal when all the WebGL commands are finished. // The related gl().wait_sync call is performed in the WR thread. See WebGLExternalImageApi for mor details. @@ -221,16 +201,13 @@ impl WebGLThread { // Without proper flushing, the sync object may never be signaled. data.ctx.gl().flush(); - sender - .send((info.texture_id, info.size, gl_sync as usize)) - .unwrap(); + sender.send((info.texture_id, info.size, gl_sync as usize)).unwrap(); } /// Handles an unlock external callback received from webrender::ExternalImageHandler fn handle_unlock(&mut self, context_id: WebGLContextId) { - let data = - Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) - .expect("WebGLContext not found in a WebGLMsg::Unlock message"); + let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found in a WebGLMsg::Unlock message"); let info = self.cached_context_info.get_mut(&context_id).unwrap(); if let Some(gl_sync) = info.gl_sync.take() { // Release the GLSync object. @@ -239,70 +216,60 @@ impl WebGLThread { } /// Creates a new WebGLContext - fn create_webgl_context( - &mut self, - version: WebGLVersion, - size: Size2D, - attributes: GLContextAttributes, - ) -> Result<(WebGLContextId, GLLimits, WebGLContextShareMode), String> { + fn create_webgl_context(&mut self, + version: WebGLVersion, + size: Size2D, + attributes: GLContextAttributes) + -> Result<(WebGLContextId, GLLimits, WebGLContextShareMode), String> { + // First try to create a shared context for the best performance. + // Fallback to readback mode if the shared context creation fails. + let result = self.gl_factory.new_shared_context(version, size, attributes) + .map(|r| (r, WebGLContextShareMode::SharedTexture)) + .or_else(|_| { + let ctx = self.gl_factory.new_context(version, size, attributes); + ctx.map(|r| (r, WebGLContextShareMode::Readback)) + }); + // Creating a new GLContext may make the current bound context_id dirty. // Clear it to ensure that make_current() is called in subsequent commands. self.bound_context_id = None; - // First try to create a shared context for the best performance. - // Fallback to readback mode if the shared context creation fails. - let (ctx, share_mode) = self - .gl_factory - .new_shared_context(version, size, attributes) - .map(|r| (r, WebGLContextShareMode::SharedTexture)) - .or_else(|err| { - warn!( - "Couldn't create shared GL context ({}), using slow readback context instead.", - err - ); - let ctx = self.gl_factory.new_context(version, size, attributes)?; - Ok((ctx, WebGLContextShareMode::Readback)) - }) - .map_err(|msg: &str| msg.to_owned())?; - - let id = WebGLContextId(self.next_webgl_id); - let (size, texture_id, limits) = ctx.get_info(); - self.next_webgl_id += 1; - self.contexts.insert( - id, - GLContextData { - ctx, - state: Default::default(), - }, - ); - self.cached_context_info.insert( - id, - WebGLContextInfo { - texture_id, - size, - alpha: attributes.alpha, - image_key: None, - share_mode, - gl_sync: None, - }, - ); + match result { + Ok((ctx, share_mode)) => { + let id = WebGLContextId(self.next_webgl_id); + let (size, texture_id, limits) = ctx.get_info(); + self.next_webgl_id += 1; + self.contexts.insert(id, GLContextData { + ctx, + state: Default::default(), + }); + self.cached_context_info.insert(id, WebGLContextInfo { + texture_id, + size, + alpha: attributes.alpha, + image_key: None, + share_mode, + gl_sync: None, + }); - Ok((id, limits, share_mode)) + Ok((id, limits, share_mode)) + }, + Err(msg) => { + Err(msg.to_owned()) + } + } } /// Resizes a WebGLContext - fn resize_webgl_context( - &mut self, - context_id: WebGLContextId, - size: Size2D, - sender: WebGLSender>, - ) { + fn resize_webgl_context(&mut self, + context_id: WebGLContextId, + size: Size2D, + sender: WebGLSender>) { let data = Self::make_current_if_needed_mut( context_id, &mut self.contexts, - &mut self.bound_context_id, - ) - .expect("Missing WebGL context!"); + &mut self.bound_context_id + ).expect("Missing WebGL context!"); match data.ctx.resize(size) { Ok(_) => { let (real_size, texture_id, _) = data.ctx.get_info(); @@ -315,22 +282,20 @@ impl WebGLThread { // See `handle_update_wr_image`. match (info.image_key, info.share_mode) { (Some(image_key), WebGLContextShareMode::SharedTexture) => { - Self::update_wr_external_image( - &self.webrender_api, - info.size, - info.alpha, - context_id, - image_key, - ); + Self::update_wr_external_image(&self.webrender_api, + info.size, + info.alpha, + context_id, + image_key); }, - _ => {}, + _ => {} } sender.send(Ok(())).unwrap(); }, Err(msg) => { sender.send(Err(msg.into())).unwrap(); - }, + } } } @@ -359,11 +324,7 @@ impl WebGLThread { /// If SharedTexture is used the UpdateWebRenderImage message is sent only after a WebGLContext creation. /// If Readback is used UpdateWebRenderImage message is sent always on each layout iteration in order to /// submit the updated raw pixels. - fn handle_update_wr_image( - &mut self, - context_id: WebGLContextId, - sender: WebGLSender, - ) { + fn handle_update_wr_image(&mut self, context_id: WebGLContextId, sender: WebGLSender) { let info = self.cached_context_info.get_mut(&context_id).unwrap(); let webrender_api = &self.webrender_api; @@ -383,29 +344,25 @@ impl WebGLThread { Some(image_key) => { // ImageKey was already created, but WR Images must // be updated every frame in readback mode to send the new raw pixels. - Self::update_wr_readback_image( - webrender_api, - info.size, - info.alpha, - image_key, - pixels, - ); + Self::update_wr_readback_image(webrender_api, + info.size, + info.alpha, + image_key, + pixels); image_key }, None => { // Generate a new ImageKey for Readback mode. - let image_key = Self::create_wr_readback_image( - webrender_api, - info.size, - info.alpha, - pixels, - ); + let image_key = Self::create_wr_readback_image(webrender_api, + info.size, + info.alpha, + pixels); info.image_key = Some(image_key); image_key - }, + } } - }, + } }; // Send the ImageKey to the Layout thread. @@ -415,12 +372,8 @@ impl WebGLThread { fn handle_dom_to_texture(&mut self, command: DOMToTextureCommand) { match command { DOMToTextureCommand::Attach(context_id, texture_id, document_id, pipeline_id, size) => { - let data = Self::make_current_if_needed( - context_id, - &self.contexts, - &mut self.bound_context_id, - ) - .expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command"); + let data = Self::make_current_if_needed(context_id, &self.contexts, &mut self.bound_context_id) + .expect("WebGLContext not found in a WebGL DOMToTextureCommand::Attach command"); // Initialize the texture that WR will use for frame outputs. data.ctx.gl().tex_image_2d( gl::TEXTURE_2D, @@ -431,17 +384,11 @@ impl WebGLThread { 0, gl::RGBA, gl::UNSIGNED_BYTE, - None, - ); - self.dom_outputs.insert( - pipeline_id, - DOMToTextureData { - context_id, - texture_id, - document_id, - size, - }, + None ); + self.dom_outputs.insert(pipeline_id, DOMToTextureData { + context_id, texture_id, document_id, size + }); let mut txn = webrender_api::Transaction::new(); txn.enable_frame_output(pipeline_id, true); self.webrender_api.send_transaction(document_id, txn); @@ -450,18 +397,12 @@ impl WebGLThread { let contexts = &self.contexts; let bound_context_id = &mut self.bound_context_id; let result = self.dom_outputs.get(&pipeline_id).and_then(|dom_data| { - let data = Self::make_current_if_needed( - dom_data.context_id, - contexts, - bound_context_id, - ); + let data = Self::make_current_if_needed(dom_data.context_id, contexts, bound_context_id); data.and_then(|data| { // The next glWaitSync call is used to synchronize the two flows of // OpenGL commands (WR and WebGL) in order to avoid using semi-ready WR textures. // glWaitSync doesn't block WebGL CPU thread. - data.ctx - .gl() - .wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); + data.ctx.gl().wait_sync(gl_sync as gl::GLsync, 0, gl::TIMEOUT_IGNORED); Some((dom_data.texture_id.get(), dom_data.size)) }) }); @@ -470,12 +411,9 @@ impl WebGLThread { sender.send(result).unwrap(); }, DOMToTextureCommand::Detach(texture_id) => { - if let Some((pipeline_id, document_id)) = self - .dom_outputs - .iter() - .find(|&(_, v)| v.texture_id == texture_id) - .map(|(k, v)| (*k, v.document_id)) - { + if let Some((pipeline_id, document_id)) = self.dom_outputs.iter() + .find(|&(_, v)| v.texture_id == texture_id) + .map(|(k, v)| (*k, v.document_id)) { let mut txn = webrender_api::Transaction::new(); txn.enable_frame_output(pipeline_id, false); self.webrender_api.send_transaction(document_id, txn); @@ -486,11 +424,9 @@ impl WebGLThread { } /// Gets a reference to a GLContextWrapper for a given WebGLContextId and makes it current if required. - fn make_current_if_needed<'a>( - context_id: WebGLContextId, - contexts: &'a FnvHashMap, - bound_id: &mut Option, - ) -> Option<&'a GLContextData> { + fn make_current_if_needed<'a>(context_id: WebGLContextId, + contexts: &'a FnvHashMap, + bound_id: &mut Option) -> Option<&'a GLContextData> { let data = contexts.get(&context_id); if let Some(data) = data { @@ -507,8 +443,9 @@ impl WebGLThread { fn make_current_if_needed_mut<'a>( context_id: WebGLContextId, contexts: &'a mut FnvHashMap, - bound_id: &mut Option, - ) -> Option<&'a mut GLContextData> { + bound_id: &mut Option) + -> Option<&'a mut GLContextData> + { let data = contexts.get_mut(&context_id); if let Some(ref data) = data { @@ -522,12 +459,10 @@ impl WebGLThread { } /// Creates a `webrender_api::ImageKey` that uses shared textures. - fn create_wr_external_image( - webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - context_id: WebGLContextId, - ) -> webrender_api::ImageKey { + fn create_wr_external_image(webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + context_id: WebGLContextId) -> webrender_api::ImageKey { let descriptor = Self::image_descriptor(size, alpha); let data = Self::external_image_data(context_id); @@ -540,13 +475,11 @@ impl WebGLThread { } /// Updates a `webrender_api::ImageKey` that uses shared textures. - fn update_wr_external_image( - webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - context_id: WebGLContextId, - image_key: webrender_api::ImageKey, - ) { + fn update_wr_external_image(webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + context_id: WebGLContextId, + image_key: webrender_api::ImageKey) { let descriptor = Self::image_descriptor(size, alpha); let data = Self::external_image_data(context_id); @@ -556,12 +489,10 @@ impl WebGLThread { } /// Creates a `webrender_api::ImageKey` that uses raw pixels. - fn create_wr_readback_image( - webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - data: Vec, - ) -> webrender_api::ImageKey { + fn create_wr_readback_image(webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + data: Vec) -> webrender_api::ImageKey { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -574,13 +505,11 @@ impl WebGLThread { } /// Updates a `webrender_api::ImageKey` that uses raw pixels. - fn update_wr_readback_image( - webrender_api: &webrender_api::RenderApi, - size: Size2D, - alpha: bool, - image_key: webrender_api::ImageKey, - data: Vec, - ) { + fn update_wr_readback_image(webrender_api: &webrender_api::RenderApi, + size: Size2D, + alpha: bool, + image_key: webrender_api::ImageKey, + data: Vec) { let descriptor = Self::image_descriptor(size, alpha); let data = webrender_api::ImageData::new(data); @@ -618,24 +547,20 @@ impl WebGLThread { let width = size.width as usize; let height = size.height as usize; - let mut pixels = context.gl().read_pixels( - 0, - 0, - size.width as gl::GLsizei, - size.height as gl::GLsizei, - gl::RGBA, - gl::UNSIGNED_BYTE, - ); + let mut pixels = context.gl().read_pixels(0, 0, + size.width as gl::GLsizei, + size.height as gl::GLsizei, + gl::RGBA, gl::UNSIGNED_BYTE); // flip image vertically (texture is upside down) let orig_pixels = pixels.clone(); let stride = width * 4; for y in 0..height { let dst_start = y * stride; let src_start = (height - y - 1) * stride; - let src_slice = &orig_pixels[src_start..src_start + stride]; - (&mut pixels[dst_start..dst_start + stride]).clone_from_slice(&src_slice[..stride]); + let src_slice = &orig_pixels[src_start .. src_start + stride]; + (&mut pixels[dst_start .. dst_start + stride]).clone_from_slice(&src_slice[..stride]); } - pixels::byte_swap_colors_inplace(&mut pixels); + byte_swap(&mut pixels); pixels } @@ -644,16 +569,13 @@ impl WebGLThread { let version = context.gl().get_string(gl::SHADING_LANGUAGE_VERSION); // Fomat used by SHADING_LANGUAGE_VERSION query : major.minor[.release] [vendor info] let mut values = version.split(&['.', ' '][..]); - let major = values - .next() - .and_then(|v| v.parse::().ok()) - .unwrap_or(1); - let minor = values - .next() - .and_then(|v| v.parse::().ok()) - .unwrap_or(20); - - WebGLSLVersion { major, minor } + let major = values.next().and_then(|v| v.parse::().ok()).unwrap_or(1); + let minor = values.next().and_then(|v| v.parse::().ok()).unwrap_or(20); + + WebGLSLVersion { + major, + minor, + } } } @@ -701,30 +623,37 @@ pub struct WebGLExternalImageHandler { impl WebGLExternalImageHandler { pub fn new(handler: T) -> Self { - Self { handler: handler } + Self { + handler: handler + } } } impl webrender::ExternalImageHandler for WebGLExternalImageHandler { /// Lock the external image. Then, WR could start to read the image content. /// The WR client should not change the image content until the unlock() call. - fn lock( - &mut self, - key: webrender_api::ExternalImageId, - _channel_index: u8, - _rendering: webrender_api::ImageRendering, - ) -> webrender::ExternalImage { + fn lock(&mut self, + key: webrender_api::ExternalImageId, + _channel_index: u8) -> webrender::ExternalImage { let ctx_id = WebGLContextId(key.0 as _); let (texture_id, size) = self.handler.lock(ctx_id); webrender::ExternalImage { - uv: webrender_api::TexelRect::new(0.0, size.height as f32, size.width as f32, 0.0), + uv: webrender_api::TexelRect::new( + 0.0, + size.height as f32, + size.width as f32, + 0.0, + ), source: webrender::ExternalImageSource::NativeTexture(texture_id), } + } /// Unlock the external image. The WR should not read the image content /// after this call. - fn unlock(&mut self, key: webrender_api::ExternalImageId, _channel_index: u8) { + fn unlock(&mut self, + key: webrender_api::ExternalImageId, + _channel_index: u8) { let ctx_id = WebGLContextId(key.0 as _); self.handler.unlock(ctx_id); } @@ -750,109 +679,82 @@ impl WebGLImpl { _backtrace: WebGLCommandBacktrace, ) { match command { - WebGLCommand::GetContextAttributes(ref sender) => { - sender.send(*ctx.borrow_attributes()).unwrap() - }, - WebGLCommand::ActiveTexture(target) => ctx.gl().active_texture(target), - WebGLCommand::AttachShader(program_id, shader_id) => { - ctx.gl().attach_shader(program_id.get(), shader_id.get()) - }, - WebGLCommand::DetachShader(program_id, shader_id) => { - ctx.gl().detach_shader(program_id.get(), shader_id.get()) - }, - WebGLCommand::BindAttribLocation(program_id, index, ref name) => ctx - .gl() - .bind_attrib_location(program_id.get(), index, &to_name_in_compiled_shader(name)), - WebGLCommand::BlendColor(r, g, b, a) => ctx.gl().blend_color(r, g, b, a), - WebGLCommand::BlendEquation(mode) => ctx.gl().blend_equation(mode), - WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha) => { - ctx.gl().blend_equation_separate(mode_rgb, mode_alpha) - }, - WebGLCommand::BlendFunc(src, dest) => ctx.gl().blend_func(src, dest), - WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) => ctx - .gl() - .blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha), + WebGLCommand::GetContextAttributes(ref sender) => + sender.send(*ctx.borrow_attributes()).unwrap(), + WebGLCommand::ActiveTexture(target) => + ctx.gl().active_texture(target), + WebGLCommand::AttachShader(program_id, shader_id) => + ctx.gl().attach_shader(program_id.get(), shader_id.get()), + WebGLCommand::DetachShader(program_id, shader_id) => + ctx.gl().detach_shader(program_id.get(), shader_id.get()), + WebGLCommand::BindAttribLocation(program_id, index, ref name) => { + ctx.gl().bind_attrib_location(program_id.get(), index, &to_name_in_compiled_shader(name)) + } + WebGLCommand::BlendColor(r, g, b, a) => + ctx.gl().blend_color(r, g, b, a), + WebGLCommand::BlendEquation(mode) => + ctx.gl().blend_equation(mode), + WebGLCommand::BlendEquationSeparate(mode_rgb, mode_alpha) => + ctx.gl().blend_equation_separate(mode_rgb, mode_alpha), + WebGLCommand::BlendFunc(src, dest) => + ctx.gl().blend_func(src, dest), + WebGLCommand::BlendFuncSeparate(src_rgb, dest_rgb, src_alpha, dest_alpha) => + ctx.gl().blend_func_separate(src_rgb, dest_rgb, src_alpha, dest_alpha), WebGLCommand::BufferData(buffer_type, ref receiver, usage) => { gl::buffer_data(ctx.gl(), buffer_type, &receiver.recv().unwrap(), usage) }, WebGLCommand::BufferSubData(buffer_type, offset, ref receiver) => { gl::buffer_sub_data(ctx.gl(), buffer_type, offset, &receiver.recv().unwrap()) }, - WebGLCommand::Clear(mask) => ctx.gl().clear(mask), + WebGLCommand::Clear(mask) => + ctx.gl().clear(mask), WebGLCommand::ClearColor(r, g, b, a) => { state.clear_color = (r, g, b, a); ctx.gl().clear_color(r, g, b, a); - }, + } WebGLCommand::ClearDepth(depth) => { let value = depth.max(0.).min(1.) as f64; state.depth_clear_value = value; ctx.gl().clear_depth(value) - }, + } WebGLCommand::ClearStencil(stencil) => { state.stencil_clear_value = stencil; ctx.gl().clear_stencil(stencil); - }, - WebGLCommand::ColorMask(r, g, b, a) => ctx.gl().color_mask(r, g, b, a), - WebGLCommand::CopyTexImage2D( - target, - level, - internal_format, - x, - y, - width, - height, - border, - ) => ctx.gl().copy_tex_image_2d( - target, - level, - internal_format, - x, - y, - width, - height, - border, - ), - WebGLCommand::CopyTexSubImage2D( - target, - level, - xoffset, - yoffset, - x, - y, - width, - height, - ) => ctx - .gl() - .copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height), - WebGLCommand::CullFace(mode) => ctx.gl().cull_face(mode), - WebGLCommand::DepthFunc(func) => ctx.gl().depth_func(func), + } + WebGLCommand::ColorMask(r, g, b, a) => + ctx.gl().color_mask(r, g, b, a), + WebGLCommand::CopyTexImage2D(target, level, internal_format, x, y, width, height, border) => + ctx.gl().copy_tex_image_2d(target, level, internal_format, x, y, width, height, border), + WebGLCommand::CopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height) => + ctx.gl().copy_tex_sub_image_2d(target, level, xoffset, yoffset, x, y, width, height), + WebGLCommand::CullFace(mode) => + ctx.gl().cull_face(mode), + WebGLCommand::DepthFunc(func) => + ctx.gl().depth_func(func), WebGLCommand::DepthMask(flag) => { state.depth_write_mask = flag; ctx.gl().depth_mask(flag); - }, - WebGLCommand::DepthRange(near, far) => ctx - .gl() - .depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64), + } + WebGLCommand::DepthRange(near, far) => { + ctx.gl().depth_range(near.max(0.).min(1.) as f64, far.max(0.).min(1.) as f64) + } WebGLCommand::Disable(cap) => { if cap == gl::SCISSOR_TEST { state.scissor_test_enabled = false; } ctx.gl().disable(cap); - }, + } WebGLCommand::Enable(cap) => { if cap == gl::SCISSOR_TEST { state.scissor_test_enabled = true; } ctx.gl().enable(cap); - }, + } WebGLCommand::FramebufferRenderbuffer(target, attachment, renderbuffertarget, rb) => { let attach = |attachment| { - ctx.gl().framebuffer_renderbuffer( - target, - attachment, - renderbuffertarget, - rb.map_or(0, WebGLRenderbufferId::get), - ) + ctx.gl().framebuffer_renderbuffer(target, attachment, + renderbuffertarget, + rb.map_or(0, WebGLRenderbufferId::get)) }; if attachment == gl::DEPTH_STENCIL_ATTACHMENT { attach(gl::DEPTH_ATTACHMENT); @@ -860,16 +762,11 @@ impl WebGLImpl { } else { attach(attachment); } - }, + } WebGLCommand::FramebufferTexture2D(target, attachment, textarget, texture, level) => { let attach = |attachment| { - ctx.gl().framebuffer_texture_2d( - target, - attachment, - textarget, - texture.map_or(0, WebGLTextureId::get), - level, - ) + ctx.gl().framebuffer_texture_2d(target, attachment, textarget, + texture.map_or(0, WebGLTextureId::get), level) }; if attachment == gl::DEPTH_STENCIL_ATTACHMENT { attach(gl::DEPTH_ATTACHMENT); @@ -877,47 +774,38 @@ impl WebGLImpl { } else { attach(attachment) } - }, - WebGLCommand::FrontFace(mode) => ctx.gl().front_face(mode), - WebGLCommand::DisableVertexAttribArray(attrib_id) => { - ctx.gl().disable_vertex_attrib_array(attrib_id) - }, - WebGLCommand::EnableVertexAttribArray(attrib_id) => { - ctx.gl().enable_vertex_attrib_array(attrib_id) - }, - WebGLCommand::Hint(name, val) => ctx.gl().hint(name, val), - WebGLCommand::LineWidth(width) => ctx.gl().line_width(width), - WebGLCommand::PixelStorei(name, val) => ctx.gl().pixel_store_i(name, val), - WebGLCommand::PolygonOffset(factor, units) => ctx.gl().polygon_offset(factor, units), - WebGLCommand::ReadPixels(rect, format, pixel_type, ref sender) => { - let pixels = ctx.gl().read_pixels( - rect.origin.x as i32, - rect.origin.y as i32, - rect.size.width as i32, - rect.size.height as i32, - format, - pixel_type, - ); - sender.send(&pixels).unwrap(); - }, - WebGLCommand::RenderbufferStorage(target, format, width, height) => { - ctx.gl().renderbuffer_storage(target, format, width, height) - }, - WebGLCommand::SampleCoverage(value, invert) => ctx.gl().sample_coverage(value, invert), - WebGLCommand::Scissor(x, y, width, height) => { - // FIXME(nox): Kinda unfortunate that some u32 values could - // end up as negative numbers here, but I don't even think - // that can happen in the real world. - ctx.gl().scissor(x, y, width as i32, height as i32); - }, - WebGLCommand::StencilFunc(func, ref_, mask) => ctx.gl().stencil_func(func, ref_, mask), - WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) => { - ctx.gl().stencil_func_separate(face, func, ref_, mask) - }, + } + WebGLCommand::FrontFace(mode) => + ctx.gl().front_face(mode), + WebGLCommand::DisableVertexAttribArray(attrib_id) => + ctx.gl().disable_vertex_attrib_array(attrib_id), + WebGLCommand::EnableVertexAttribArray(attrib_id) => + ctx.gl().enable_vertex_attrib_array(attrib_id), + WebGLCommand::Hint(name, val) => + ctx.gl().hint(name, val), + WebGLCommand::LineWidth(width) => + ctx.gl().line_width(width), + WebGLCommand::PixelStorei(name, val) => + ctx.gl().pixel_store_i(name, val), + WebGLCommand::PolygonOffset(factor, units) => + ctx.gl().polygon_offset(factor, units), + WebGLCommand::ReadPixels(x, y, width, height, format, pixel_type, ref chan) => { + Self::read_pixels(ctx.gl(), x, y, width, height, format, pixel_type, chan) + } + WebGLCommand::RenderbufferStorage(target, format, width, height) => + ctx.gl().renderbuffer_storage(target, format, width, height), + WebGLCommand::SampleCoverage(value, invert) => + ctx.gl().sample_coverage(value, invert), + WebGLCommand::Scissor(x, y, width, height) => + ctx.gl().scissor(x, y, width, height), + WebGLCommand::StencilFunc(func, ref_, mask) => + ctx.gl().stencil_func(func, ref_, mask), + WebGLCommand::StencilFuncSeparate(face, func, ref_, mask) => + ctx.gl().stencil_func_separate(face, func, ref_, mask), WebGLCommand::StencilMask(mask) => { state.stencil_write_mask = (mask, mask); ctx.gl().stencil_mask(mask); - }, + } WebGLCommand::StencilMaskSeparate(face, mask) => { if face == gl::FRONT { state.stencil_write_mask.0 = mask; @@ -925,418 +813,385 @@ impl WebGLImpl { state.stencil_write_mask.1 = mask; } ctx.gl().stencil_mask_separate(face, mask); - }, - WebGLCommand::StencilOp(fail, zfail, zpass) => ctx.gl().stencil_op(fail, zfail, zpass), - WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) => { - ctx.gl().stencil_op_separate(face, fail, zfail, zpass) - }, - WebGLCommand::GetRenderbufferParameter(target, pname, ref chan) => { - Self::get_renderbuffer_parameter(ctx.gl(), target, pname, chan) - }, - WebGLCommand::GetFramebufferAttachmentParameter( - target, - attachment, - pname, - ref chan, - ) => Self::get_framebuffer_attachment_parameter( - ctx.gl(), - target, - attachment, - pname, - chan, - ), - WebGLCommand::GetShaderPrecisionFormat(shader_type, precision_type, ref chan) => { - Self::shader_precision_format(ctx.gl(), shader_type, precision_type, chan) - }, - WebGLCommand::GetExtensions(ref chan) => Self::get_extensions(ctx.gl(), chan), - WebGLCommand::GetUniformLocation(program_id, ref name, ref chan) => { - Self::uniform_location(ctx.gl(), program_id, &name, chan) - }, - WebGLCommand::GetShaderInfoLog(shader_id, ref chan) => { - Self::shader_info_log(ctx.gl(), shader_id, chan) - }, - WebGLCommand::GetProgramInfoLog(program_id, ref chan) => { - Self::program_info_log(ctx.gl(), program_id, chan) - }, - WebGLCommand::CompileShader(shader_id, ref source) => { - Self::compile_shader(ctx.gl(), shader_id, &source) - }, - WebGLCommand::CreateBuffer(ref chan) => Self::create_buffer(ctx.gl(), chan), - WebGLCommand::CreateFramebuffer(ref chan) => Self::create_framebuffer(ctx.gl(), chan), - WebGLCommand::CreateRenderbuffer(ref chan) => Self::create_renderbuffer(ctx.gl(), chan), - WebGLCommand::CreateTexture(ref chan) => Self::create_texture(ctx.gl(), chan), - WebGLCommand::CreateProgram(ref chan) => Self::create_program(ctx.gl(), chan), - WebGLCommand::CreateShader(shader_type, ref chan) => { - Self::create_shader(ctx.gl(), shader_type, chan) - }, - WebGLCommand::DeleteBuffer(id) => ctx.gl().delete_buffers(&[id.get()]), - WebGLCommand::DeleteFramebuffer(id) => ctx.gl().delete_framebuffers(&[id.get()]), - WebGLCommand::DeleteRenderbuffer(id) => ctx.gl().delete_renderbuffers(&[id.get()]), - WebGLCommand::DeleteTexture(id) => ctx.gl().delete_textures(&[id.get()]), - WebGLCommand::DeleteProgram(id) => ctx.gl().delete_program(id.get()), - WebGLCommand::DeleteShader(id) => ctx.gl().delete_shader(id.get()), - WebGLCommand::BindBuffer(target, id) => ctx - .gl() - .bind_buffer(target, id.map_or(0, WebGLBufferId::get)), - WebGLCommand::BindFramebuffer(target, request) => { - Self::bind_framebuffer(ctx.gl(), target, request, ctx) - }, - WebGLCommand::BindRenderbuffer(target, id) => ctx - .gl() - .bind_renderbuffer(target, id.map_or(0, WebGLRenderbufferId::get)), - WebGLCommand::BindTexture(target, id) => ctx - .gl() - .bind_texture(target, id.map_or(0, WebGLTextureId::get)), - WebGLCommand::Uniform1f(uniform_id, v) => ctx.gl().uniform_1f(uniform_id, v), - WebGLCommand::Uniform1fv(uniform_id, ref v) => ctx.gl().uniform_1fv(uniform_id, v), - WebGLCommand::Uniform1i(uniform_id, v) => ctx.gl().uniform_1i(uniform_id, v), - WebGLCommand::Uniform1iv(uniform_id, ref v) => ctx.gl().uniform_1iv(uniform_id, v), - WebGLCommand::Uniform2f(uniform_id, x, y) => ctx.gl().uniform_2f(uniform_id, x, y), - WebGLCommand::Uniform2fv(uniform_id, ref v) => ctx.gl().uniform_2fv(uniform_id, v), - WebGLCommand::Uniform2i(uniform_id, x, y) => ctx.gl().uniform_2i(uniform_id, x, y), - WebGLCommand::Uniform2iv(uniform_id, ref v) => ctx.gl().uniform_2iv(uniform_id, v), - WebGLCommand::Uniform3f(uniform_id, x, y, z) => { - ctx.gl().uniform_3f(uniform_id, x, y, z) - }, - WebGLCommand::Uniform3fv(uniform_id, ref v) => ctx.gl().uniform_3fv(uniform_id, v), - WebGLCommand::Uniform3i(uniform_id, x, y, z) => { - ctx.gl().uniform_3i(uniform_id, x, y, z) - }, - WebGLCommand::Uniform3iv(uniform_id, ref v) => ctx.gl().uniform_3iv(uniform_id, v), - WebGLCommand::Uniform4f(uniform_id, x, y, z, w) => { - ctx.gl().uniform_4f(uniform_id, x, y, z, w) - }, - WebGLCommand::Uniform4fv(uniform_id, ref v) => ctx.gl().uniform_4fv(uniform_id, v), - WebGLCommand::Uniform4i(uniform_id, x, y, z, w) => { - ctx.gl().uniform_4i(uniform_id, x, y, z, w) - }, - WebGLCommand::Uniform4iv(uniform_id, ref v) => ctx.gl().uniform_4iv(uniform_id, v), + } + WebGLCommand::StencilOp(fail, zfail, zpass) => + ctx.gl().stencil_op(fail, zfail, zpass), + WebGLCommand::StencilOpSeparate(face, fail, zfail, zpass) => + ctx.gl().stencil_op_separate(face, fail, zfail, zpass), + WebGLCommand::GetRenderbufferParameter(target, pname, ref chan) => + Self::get_renderbuffer_parameter(ctx.gl(), target, pname, chan), + WebGLCommand::GetFramebufferAttachmentParameter(target, attachment, pname, ref chan) => + Self::get_framebuffer_attachment_parameter(ctx.gl(), target, attachment, pname, chan), + WebGLCommand::GetShaderPrecisionFormat(shader_type, precision_type, ref chan) => + Self::shader_precision_format(ctx.gl(), shader_type, precision_type, chan), + WebGLCommand::GetExtensions(ref chan) => + Self::get_extensions(ctx.gl(), chan), + WebGLCommand::GetUniformLocation(program_id, ref name, ref chan) => + Self::uniform_location(ctx.gl(), program_id, &name, chan), + WebGLCommand::GetShaderInfoLog(shader_id, ref chan) => + Self::shader_info_log(ctx.gl(), shader_id, chan), + WebGLCommand::GetProgramInfoLog(program_id, ref chan) => + Self::program_info_log(ctx.gl(), program_id, chan), + WebGLCommand::CompileShader(shader_id, ref source) => + Self::compile_shader(ctx.gl(), shader_id, &source), + WebGLCommand::CreateBuffer(ref chan) => + Self::create_buffer(ctx.gl(), chan), + WebGLCommand::CreateFramebuffer(ref chan) => + Self::create_framebuffer(ctx.gl(), chan), + WebGLCommand::CreateRenderbuffer(ref chan) => + Self::create_renderbuffer(ctx.gl(), chan), + WebGLCommand::CreateTexture(ref chan) => + Self::create_texture(ctx.gl(), chan), + WebGLCommand::CreateProgram(ref chan) => + Self::create_program(ctx.gl(), chan), + WebGLCommand::CreateShader(shader_type, ref chan) => + Self::create_shader(ctx.gl(), shader_type, chan), + WebGLCommand::DeleteBuffer(id) => + ctx.gl().delete_buffers(&[id.get()]), + WebGLCommand::DeleteFramebuffer(id) => + ctx.gl().delete_framebuffers(&[id.get()]), + WebGLCommand::DeleteRenderbuffer(id) => + ctx.gl().delete_renderbuffers(&[id.get()]), + WebGLCommand::DeleteTexture(id) => + ctx.gl().delete_textures(&[id.get()]), + WebGLCommand::DeleteProgram(id) => + ctx.gl().delete_program(id.get()), + WebGLCommand::DeleteShader(id) => + ctx.gl().delete_shader(id.get()), + WebGLCommand::BindBuffer(target, id) => + ctx.gl().bind_buffer(target, id.map_or(0, WebGLBufferId::get)), + WebGLCommand::BindFramebuffer(target, request) => + Self::bind_framebuffer(ctx.gl(), target, request, ctx), + WebGLCommand::BindRenderbuffer(target, id) => + ctx.gl().bind_renderbuffer(target, id.map_or(0, WebGLRenderbufferId::get)), + WebGLCommand::BindTexture(target, id) => + ctx.gl().bind_texture(target, id.map_or(0, WebGLTextureId::get)), + WebGLCommand::Uniform1f(uniform_id, v) => + ctx.gl().uniform_1f(uniform_id, v), + WebGLCommand::Uniform1fv(uniform_id, ref v) => + ctx.gl().uniform_1fv(uniform_id, v), + WebGLCommand::Uniform1i(uniform_id, v) => + ctx.gl().uniform_1i(uniform_id, v), + WebGLCommand::Uniform1iv(uniform_id, ref v) => + ctx.gl().uniform_1iv(uniform_id, v), + WebGLCommand::Uniform2f(uniform_id, x, y) => + ctx.gl().uniform_2f(uniform_id, x, y), + WebGLCommand::Uniform2fv(uniform_id, ref v) => + ctx.gl().uniform_2fv(uniform_id, v), + WebGLCommand::Uniform2i(uniform_id, x, y) => + ctx.gl().uniform_2i(uniform_id, x, y), + WebGLCommand::Uniform2iv(uniform_id, ref v) => + ctx.gl().uniform_2iv(uniform_id, v), + WebGLCommand::Uniform3f(uniform_id, x, y, z) => + ctx.gl().uniform_3f(uniform_id, x, y, z), + WebGLCommand::Uniform3fv(uniform_id, ref v) => + ctx.gl().uniform_3fv(uniform_id, v), + WebGLCommand::Uniform3i(uniform_id, x, y, z) => + ctx.gl().uniform_3i(uniform_id, x, y, z), + WebGLCommand::Uniform3iv(uniform_id, ref v) => + ctx.gl().uniform_3iv(uniform_id, v), + WebGLCommand::Uniform4f(uniform_id, x, y, z, w) => + ctx.gl().uniform_4f(uniform_id, x, y, z, w), + WebGLCommand::Uniform4fv(uniform_id, ref v) => + ctx.gl().uniform_4fv(uniform_id, v), + WebGLCommand::Uniform4i(uniform_id, x, y, z, w) => + ctx.gl().uniform_4i(uniform_id, x, y, z, w), + WebGLCommand::Uniform4iv(uniform_id, ref v) => + ctx.gl().uniform_4iv(uniform_id, v), WebGLCommand::UniformMatrix2fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_2fv(uniform_id, false, v) - }, + } WebGLCommand::UniformMatrix3fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_3fv(uniform_id, false, v) - }, + } WebGLCommand::UniformMatrix4fv(uniform_id, ref v) => { ctx.gl().uniform_matrix_4fv(uniform_id, false, v) - }, - WebGLCommand::ValidateProgram(program_id) => { - ctx.gl().validate_program(program_id.get()) - }, - WebGLCommand::VertexAttrib(attrib_id, x, y, z, w) => { - ctx.gl().vertex_attrib_4f(attrib_id, x, y, z, w) - }, - WebGLCommand::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset) => ctx - .gl() - .vertex_attrib_pointer_f32(attrib_id, size, normalized, stride, offset), - WebGLCommand::VertexAttribPointer( - attrib_id, - size, - data_type, - normalized, - stride, - offset, - ) => ctx - .gl() - .vertex_attrib_pointer(attrib_id, size, data_type, normalized, stride, offset), + } + WebGLCommand::ValidateProgram(program_id) => + ctx.gl().validate_program(program_id.get()), + WebGLCommand::VertexAttrib(attrib_id, x, y, z, w) => + ctx.gl().vertex_attrib_4f(attrib_id, x, y, z, w), + WebGLCommand::VertexAttribPointer2f(attrib_id, size, normalized, stride, offset) => + ctx.gl().vertex_attrib_pointer_f32(attrib_id, size, normalized, stride, offset), + WebGLCommand::VertexAttribPointer(attrib_id, size, data_type, normalized, stride, offset) => + ctx.gl().vertex_attrib_pointer(attrib_id, size, data_type, normalized, stride, offset), WebGLCommand::SetViewport(x, y, width, height) => { ctx.gl().viewport(x, y, width, height); - }, - WebGLCommand::TexImage2D( - target, - level, - internal, - width, - height, - format, - data_type, - ref chan, - ) => ctx.gl().tex_image_2d( - target, - level, - internal, - width, - height, - 0, - format, - data_type, - Some(&chan.recv().unwrap()), - ), - WebGLCommand::TexSubImage2D( - target, - level, - xoffset, - yoffset, - x, - y, - width, - height, - ref chan, - ) => ctx.gl().tex_sub_image_2d( - target, - level, - xoffset, - yoffset, - x, - y, - width, - height, - &chan.recv().unwrap(), - ), - WebGLCommand::DrawingBufferWidth(ref sender) => sender - .send(ctx.borrow_draw_buffer().unwrap().size().width) - .unwrap(), - WebGLCommand::DrawingBufferHeight(ref sender) => sender - .send(ctx.borrow_draw_buffer().unwrap().size().height) - .unwrap(), - WebGLCommand::Finish(ref sender) => Self::finish(ctx.gl(), sender), - WebGLCommand::Flush => ctx.gl().flush(), - WebGLCommand::GenerateMipmap(target) => ctx.gl().generate_mipmap(target), - WebGLCommand::CreateVertexArray(ref chan) => Self::create_vertex_array(ctx.gl(), chan), - WebGLCommand::DeleteVertexArray(id) => ctx.gl().delete_vertex_arrays(&[id.get()]), - WebGLCommand::BindVertexArray(id) => ctx - .gl() - .bind_vertex_array(id.map_or(0, WebGLVertexArrayId::get)), + } + WebGLCommand::TexImage2D(target, level, internal, width, height, format, data_type, ref chan) => { + ctx.gl().tex_image_2d( + target, + level, + internal, + width, + height, + 0, + format, + data_type, + Some(&chan.recv().unwrap()), + ) + } + WebGLCommand::TexSubImage2D(target, level, xoffset, yoffset, x, y, width, height, ref chan) => { + ctx.gl().tex_sub_image_2d( + target, + level, + xoffset, + yoffset, + x, + y, + width, + height, + &chan.recv().unwrap(), + ) + } + WebGLCommand::DrawingBufferWidth(ref sender) => + sender.send(ctx.borrow_draw_buffer().unwrap().size().width).unwrap(), + WebGLCommand::DrawingBufferHeight(ref sender) => + sender.send(ctx.borrow_draw_buffer().unwrap().size().height).unwrap(), + WebGLCommand::Finish(ref sender) => + Self::finish(ctx.gl(), sender), + WebGLCommand::Flush => + ctx.gl().flush(), + WebGLCommand::GenerateMipmap(target) => + ctx.gl().generate_mipmap(target), + WebGLCommand::CreateVertexArray(ref chan) => + Self::create_vertex_array(ctx.gl(), chan), + WebGLCommand::DeleteVertexArray(id) => + ctx.gl().delete_vertex_arrays(&[id.get()]), + WebGLCommand::BindVertexArray(id) => + ctx.gl().bind_vertex_array(id.map_or(0, WebGLVertexArrayId::get)), WebGLCommand::GetParameterBool(param, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_boolean_v(param as u32, &mut value); } sender.send(value[0] != 0).unwrap() - }, + } WebGLCommand::GetParameterBool4(param, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_boolean_v(param as u32, &mut value); } - let value = [value[0] != 0, value[1] != 0, value[2] != 0, value[3] != 0]; + let value = [ + value[0] != 0, + value[1] != 0, + value[2] != 0, + value[3] != 0, + ]; sender.send(value).unwrap() - }, + } WebGLCommand::GetParameterInt(param, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value[0]).unwrap() - }, + } WebGLCommand::GetParameterInt2(param, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value).unwrap() - }, + } WebGLCommand::GetParameterInt4(param, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_integer_v(param as u32, &mut value); } sender.send(value).unwrap() - }, + } WebGLCommand::GetParameterFloat(param, ref sender) => { let mut value = [0.]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value[0]).unwrap() - }, + } WebGLCommand::GetParameterFloat2(param, ref sender) => { let mut value = [0.; 2]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value).unwrap() - }, + } WebGLCommand::GetParameterFloat4(param, ref sender) => { let mut value = [0.; 4]; unsafe { ctx.gl().get_float_v(param as u32, &mut value); } sender.send(value).unwrap() - }, + } WebGLCommand::GetProgramValidateStatus(program, ref sender) => { let mut value = [0]; unsafe { - ctx.gl() - .get_program_iv(program.get(), gl::VALIDATE_STATUS, &mut value); + ctx.gl().get_program_iv(program.get(), gl::VALIDATE_STATUS, &mut value); } sender.send(value[0] != 0).unwrap() - }, + } WebGLCommand::GetProgramActiveUniforms(program, ref sender) => { let mut value = [0]; unsafe { - ctx.gl() - .get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut value); + ctx.gl().get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut value); } sender.send(value[0]).unwrap() - }, + } WebGLCommand::GetCurrentVertexAttrib(index, ref sender) => { let mut value = [0.; 4]; unsafe { - ctx.gl() - .get_vertex_attrib_fv(index, gl::CURRENT_VERTEX_ATTRIB, &mut value); + ctx.gl().get_vertex_attrib_fv(index, gl::CURRENT_VERTEX_ATTRIB, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetTexParameterFloat(target, param, ref sender) => { - sender - .send(ctx.gl().get_tex_parameter_fv(target, param as u32)) - .unwrap(); - }, + sender.send(ctx.gl().get_tex_parameter_fv(target, param as u32)).unwrap(); + } WebGLCommand::GetTexParameterInt(target, param, ref sender) => { - sender - .send(ctx.gl().get_tex_parameter_iv(target, param as u32)) - .unwrap(); - }, + sender.send(ctx.gl().get_tex_parameter_iv(target, param as u32)).unwrap(); + } WebGLCommand::TexParameteri(target, param, value) => { ctx.gl().tex_parameter_i(target, param as u32, value) - }, + } WebGLCommand::TexParameterf(target, param, value) => { ctx.gl().tex_parameter_f(target, param as u32, value) - }, + } WebGLCommand::LinkProgram(program_id, ref sender) => { - return sender - .send(Self::link_program(ctx.gl(), program_id)) - .unwrap(); - }, + return sender.send(Self::link_program(ctx.gl(), program_id)).unwrap(); + } WebGLCommand::UseProgram(program_id) => { ctx.gl().use_program(program_id.map_or(0, |p| p.get())) - }, + } WebGLCommand::DrawArrays { mode, first, count } => { ctx.gl().draw_arrays(mode, first, count) - }, - WebGLCommand::DrawArraysInstanced { - mode, - first, - count, - primcount, - } => ctx - .gl() - .draw_arrays_instanced(mode, first, count, primcount), - WebGLCommand::DrawElements { - mode, - count, - type_, - offset, - } => ctx.gl().draw_elements(mode, count, type_, offset), - WebGLCommand::DrawElementsInstanced { - mode, - count, - type_, - offset, - primcount, - } => ctx - .gl() - .draw_elements_instanced(mode, count, type_, offset, primcount), + } + WebGLCommand::DrawArraysInstanced { mode, first, count, primcount } => { + ctx.gl().draw_arrays_instanced(mode, first, count, primcount) + } + WebGLCommand::DrawElements { mode, count, type_, offset } => { + ctx.gl().draw_elements(mode, count, type_, offset) + } + WebGLCommand::DrawElementsInstanced { mode, count, type_, offset, primcount } => { + ctx.gl().draw_elements_instanced(mode, count, type_, offset, primcount) + } WebGLCommand::VertexAttribDivisor { index, divisor } => { ctx.gl().vertex_attrib_divisor(index, divisor) - }, + } WebGLCommand::GetUniformBool(program_id, loc, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value[0] != 0).unwrap(); - }, + } WebGLCommand::GetUniformBool2(program_id, loc, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [value[0] != 0, value[1] != 0]; + let value = [ + value[0] != 0, + value[1] != 0, + ]; sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformBool3(program_id, loc, ref sender) => { let mut value = [0; 3]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [value[0] != 0, value[1] != 0, value[2] != 0]; + let value = [ + value[0] != 0, + value[1] != 0, + value[2] != 0, + ]; sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformBool4(program_id, loc, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } - let value = [value[0] != 0, value[1] != 0, value[2] != 0, value[3] != 0]; + let value = [ + value[0] != 0, + value[1] != 0, + value[2] != 0, + value[3] != 0, + ]; sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformInt(program_id, loc, ref sender) => { let mut value = [0]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value[0]).unwrap(); - }, + } WebGLCommand::GetUniformInt2(program_id, loc, ref sender) => { let mut value = [0; 2]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformInt3(program_id, loc, ref sender) => { let mut value = [0; 3]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformInt4(program_id, loc, ref sender) => { let mut value = [0; 4]; unsafe { ctx.gl().get_uniform_iv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformFloat(program_id, loc, ref sender) => { let mut value = [0.]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value[0]).unwrap(); - }, + } WebGLCommand::GetUniformFloat2(program_id, loc, ref sender) => { let mut value = [0.; 2]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformFloat3(program_id, loc, ref sender) => { let mut value = [0.; 3]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformFloat4(program_id, loc, ref sender) => { let mut value = [0.; 4]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformFloat9(program_id, loc, ref sender) => { let mut value = [0.; 9]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, + } WebGLCommand::GetUniformFloat16(program_id, loc, ref sender) => { let mut value = [0.; 16]; unsafe { ctx.gl().get_uniform_fv(program_id.get(), loc, &mut value); } sender.send(value).unwrap(); - }, - WebGLCommand::InitializeFramebuffer { - color, - depth, - stencil, - } => Self::initialize_framebuffer(ctx.gl(), state, color, depth, stencil), + } + WebGLCommand::InitializeFramebuffer { color, depth, stencil } => { + Self::initialize_framebuffer(ctx.gl(), state, color, depth, stencil) + } } // TODO: update test expectations in order to enable debug assertions @@ -1351,17 +1206,11 @@ impl WebGLImpl { } } } - assert_eq!( - error, - gl::NO_ERROR, - "Unexpected WebGL error: 0x{:x} ({})", - error, - error - ); + assert_eq!(error, gl::NO_ERROR, "Unexpected WebGL error: 0x{:x} ({})", error, error); } fn initialize_framebuffer( - gl: &dyn gl::Gl, + gl: &gl::Gl, state: &GLState, color: bool, depth: bool, @@ -1371,11 +1220,7 @@ impl WebGLImpl { (color, gl::COLOR_BUFFER_BIT), (depth, gl::DEPTH_BUFFER_BIT), (stencil, gl::STENCIL_BUFFER_BIT), - ] - .iter() - .fold(0, |bits, &(enabled, bit)| { - bits | if enabled { bit } else { 0 } - }); + ].iter().fold(0, |bits, &(enabled, bit)| bits | if enabled { bit } else { 0 }); if state.scissor_test_enabled { gl.disable(gl::SCISSOR_TEST); @@ -1421,7 +1266,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn link_program(gl: &dyn gl::Gl, program: WebGLProgramId) -> ProgramLinkInfo { + fn link_program(gl: &gl::Gl, program: WebGLProgramId) -> ProgramLinkInfo { gl.link_program(program.get()); let mut linked = [0]; unsafe { @@ -1432,60 +1277,50 @@ impl WebGLImpl { linked: false, active_attribs: vec![].into(), active_uniforms: vec![].into(), - }; + } } let mut num_active_attribs = [0]; unsafe { - gl.get_program_iv( - program.get(), - gl::ACTIVE_ATTRIBUTES, - &mut num_active_attribs, - ); + gl.get_program_iv(program.get(), gl::ACTIVE_ATTRIBUTES, &mut num_active_attribs); } - let active_attribs = (0..num_active_attribs[0] as u32) - .map(|i| { - // FIXME(nox): This allocates strings sometimes for nothing - // and the gleam method keeps getting ACTIVE_ATTRIBUTE_MAX_LENGTH. - let (size, type_, name) = gl.get_active_attrib(program.get(), i); - let location = if name.starts_with("gl_") { - -1 - } else { - gl.get_attrib_location(program.get(), &name) - }; - ActiveAttribInfo { - name: from_name_in_compiled_shader(&name), - size, - type_, - location, - } - }) - .collect::>() - .into(); + let active_attribs = (0..num_active_attribs[0] as u32).map(|i| { + // FIXME(nox): This allocates strings sometimes for nothing + // and the gleam method keeps getting ACTIVE_ATTRIBUTE_MAX_LENGTH. + let (size, type_, name) = gl.get_active_attrib(program.get(), i); + let location = if name.starts_with("gl_") { + -1 + } else { + gl.get_attrib_location(program.get(), &name) + }; + ActiveAttribInfo { + name: from_name_in_compiled_shader(&name), + size, + type_, + location, + } + }).collect::>().into(); let mut num_active_uniforms = [0]; unsafe { gl.get_program_iv(program.get(), gl::ACTIVE_UNIFORMS, &mut num_active_uniforms); } - let active_uniforms = (0..num_active_uniforms[0] as u32) - .map(|i| { - // FIXME(nox): This allocates strings sometimes for nothing - // and the gleam method keeps getting ACTIVE_UNIFORM_MAX_LENGTH. - let (size, type_, mut name) = gl.get_active_uniform(program.get(), i); - let is_array = name.ends_with("[0]"); - if is_array { - // FIXME(nox): NLL - let len = name.len(); - name.truncate(len - 3); - } - ActiveUniformInfo { - base_name: from_name_in_compiled_shader(&name).into(), - size: if is_array { Some(size) } else { None }, - type_, - } - }) - .collect::>() - .into(); + let active_uniforms = (0..num_active_uniforms[0] as u32).map(|i| { + // FIXME(nox): This allocates strings sometimes for nothing + // and the gleam method keeps getting ACTIVE_UNIFORM_MAX_LENGTH. + let (size, type_, mut name) = gl.get_active_uniform(program.get(), i); + let is_array = name.ends_with("[0]"); + if is_array { + // FIXME(nox): NLL + let len = name.len(); + name.truncate(len - 3); + } + ActiveUniformInfo { + base_name: from_name_in_compiled_shader(&name).into(), + size: if is_array { Some(size) } else { None }, + type_, + } + }).collect::>().into(); ProgramLinkInfo { linked: true, @@ -1494,32 +1329,44 @@ impl WebGLImpl { } } - fn finish(gl: &dyn gl::Gl, chan: &WebGLSender<()>) { + fn read_pixels( + gl: &gl::Gl, + x: i32, + y: i32, + width: i32, + height: i32, + format: u32, + pixel_type: u32, + chan: &IpcBytesSender, + ) { + let result = gl.read_pixels(x, y, width, height, format, pixel_type); + chan.send(&result).unwrap() + } + + fn finish(gl: &gl::Gl, chan: &WebGLSender<()>) { gl.finish(); chan.send(()).unwrap(); } - fn shader_precision_format( - gl: &dyn gl::Gl, - shader_type: u32, - precision_type: u32, - chan: &WebGLSender<(i32, i32, i32)>, - ) { + fn shader_precision_format(gl: &gl::Gl, + shader_type: u32, + precision_type: u32, + chan: &WebGLSender<(i32, i32, i32)>) { let result = gl.get_shader_precision_format(shader_type, precision_type); chan.send(result).unwrap(); } - fn get_extensions(gl: &dyn gl::Gl, chan: &WebGLSender) { + fn get_extensions(gl: &gl::Gl, chan: &WebGLSender) { chan.send(gl.get_string(gl::EXTENSIONS)).unwrap(); } // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.6 fn get_framebuffer_attachment_parameter( - gl: &dyn gl::Gl, + gl: &gl::Gl, target: u32, attachment: u32, pname: u32, - chan: &WebGLSender, + chan: &WebGLSender ) { let parameter = gl.get_framebuffer_attachment_parameter_iv(target, attachment, pname); chan.send(parameter).unwrap(); @@ -1527,17 +1374,17 @@ impl WebGLImpl { // https://www.khronos.org/registry/webgl/specs/latest/1.0/#5.14.7 fn get_renderbuffer_parameter( - gl: &dyn gl::Gl, + gl: &gl::Gl, target: u32, pname: u32, - chan: &WebGLSender, + chan: &WebGLSender ) { let parameter = gl.get_renderbuffer_parameter_iv(target, pname); chan.send(parameter).unwrap(); } fn uniform_location( - gl: &dyn gl::Gl, + gl: &gl::Gl, program_id: WebGLProgramId, name: &str, chan: &WebGLSender, @@ -1547,18 +1394,19 @@ impl WebGLImpl { chan.send(location).unwrap(); } - fn shader_info_log(gl: &dyn gl::Gl, shader_id: WebGLShaderId, chan: &WebGLSender) { + + fn shader_info_log(gl: &gl::Gl, shader_id: WebGLShaderId, chan: &WebGLSender) { let log = gl.get_shader_info_log(shader_id.get()); chan.send(log).unwrap(); } - fn program_info_log(gl: &dyn gl::Gl, program_id: WebGLProgramId, chan: &WebGLSender) { + fn program_info_log(gl: &gl::Gl, program_id: WebGLProgramId, chan: &WebGLSender) { let log = gl.get_program_info_log(program_id.get()); chan.send(log).unwrap(); } #[allow(unsafe_code)] - fn create_buffer(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_buffer(gl: &gl::Gl, chan: &WebGLSender>) { let buffer = gl.gen_buffers(1)[0]; let buffer = if buffer == 0 { None @@ -1569,7 +1417,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_framebuffer(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_framebuffer(gl: &gl::Gl, chan: &WebGLSender>) { let framebuffer = gl.gen_framebuffers(1)[0]; let framebuffer = if framebuffer == 0 { None @@ -1580,7 +1428,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_renderbuffer(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_renderbuffer(gl: &gl::Gl, chan: &WebGLSender>) { let renderbuffer = gl.gen_renderbuffers(1)[0]; let renderbuffer = if renderbuffer == 0 { None @@ -1591,7 +1439,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_texture(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_texture(gl: &gl::Gl, chan: &WebGLSender>) { let texture = gl.gen_textures(1)[0]; let texture = if texture == 0 { None @@ -1602,7 +1450,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_program(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_program(gl: &gl::Gl, chan: &WebGLSender>) { let program = gl.create_program(); let program = if program == 0 { None @@ -1613,7 +1461,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_shader(gl: &dyn gl::Gl, shader_type: u32, chan: &WebGLSender>) { + fn create_shader(gl: &gl::Gl, shader_type: u32, chan: &WebGLSender>) { let shader = gl.create_shader(shader_type); let shader = if shader == 0 { None @@ -1624,7 +1472,7 @@ impl WebGLImpl { } #[allow(unsafe_code)] - fn create_vertex_array(gl: &dyn gl::Gl, chan: &WebGLSender>) { + fn create_vertex_array(gl: &gl::Gl, chan: &WebGLSender>) { let vao = gl.gen_vertex_arrays(1)[0]; let vao = if vao == 0 { None @@ -1635,24 +1483,22 @@ impl WebGLImpl { } #[inline] - fn bind_framebuffer( - gl: &dyn gl::Gl, - target: u32, - request: WebGLFramebufferBindingRequest, - ctx: &GLContext, - ) { + fn bind_framebuffer(gl: &gl::Gl, + target: u32, + request: WebGLFramebufferBindingRequest, + ctx: &GLContext) { let id = match request { WebGLFramebufferBindingRequest::Explicit(id) => id.get(), - WebGLFramebufferBindingRequest::Default => { - ctx.borrow_draw_buffer().unwrap().get_framebuffer() - }, + WebGLFramebufferBindingRequest::Default => + ctx.borrow_draw_buffer().unwrap().get_framebuffer(), }; gl.bind_framebuffer(target, id); } + #[inline] - fn compile_shader(gl: &dyn gl::Gl, shader_id: WebGLShaderId, source: &str) { + fn compile_shader(gl: &gl::Gl, shader_id: WebGLShaderId, source: &str) { gl.shader_source(shader_id.get(), &[source.as_bytes()]); gl.compile_shader(shader_id.get()); } diff --git a/components/canvas_traits/Cargo.toml b/components/canvas_traits/Cargo.toml index ae8eb8e4ec4c..187b46d617e1 100644 --- a/components/canvas_traits/Cargo.toml +++ b/components/canvas_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "canvas_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -14,7 +13,7 @@ path = "lib.rs" webgl_backtrace = [] [dependencies] -cssparser = "0.25" +cssparser = "0.24.0" euclid = "0.19" ipc-channel = "0.11" gleam = "0.6" diff --git a/components/canvas_traits/canvas.rs b/components/canvas_traits/canvas.rs index 6733804be636..a9d47d252a40 100644 --- a/components/canvas_traits/canvas.rs +++ b/components/canvas_traits/canvas.rs @@ -3,48 +3,44 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::RGBA; -use euclid::{Point2D, Rect, Size2D, Transform2D}; -use ipc_channel::ipc::{IpcBytesReceiver, IpcBytesSender, IpcSender}; +use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D}; +use ipc_channel::ipc::{IpcBytesSender, IpcSender}; use serde_bytes::ByteBuf; use std::default::Default; use std::str::FromStr; +use webrender_api; -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum FillRule { Nonzero, Evenodd, } -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, Eq, Hash, MallocSizeOf, PartialEq, Serialize)] pub struct CanvasId(pub u64); -#[derive(Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum CanvasMsg { Canvas2d(Canvas2dMsg, CanvasId), - Create( - IpcSender, - Size2D, - webrender_api::RenderApiSender, - bool, - ), + Create(IpcSender, Size2D, webrender_api::RenderApiSender, bool), FromLayout(FromLayoutMsg, CanvasId), FromScript(FromScriptMsg, CanvasId), - Recreate(Size2D, CanvasId), + Recreate(Size2D, CanvasId), Close(CanvasId), - Exit, } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct CanvasImageData { pub image_key: webrender_api::ImageKey, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum Canvas2dMsg { Arc(Point2D, f32, f32, f32, bool), ArcTo(Point2D, Point2D, f32), DrawImage(Option, Size2D, Rect, Rect, bool), - DrawImageInOther(CanvasId, Size2D, Rect, Rect, bool), + DrawImageInOther( + CanvasId, Size2D, Rect, Rect, bool), BeginPath, BezierCurveTo(Point2D, Point2D, Point2D), ClearRect(Rect), @@ -54,11 +50,11 @@ pub enum Canvas2dMsg { Fill, FillText(String, f64, f64, Option), FillRect(Rect), - GetImageData(Rect, Size2D, IpcBytesSender), + GetImageData(Rect, Size2D, IpcBytesSender), IsPointInPath(f64, f64, FillRule, IpcSender), LineTo(Point2D), MoveTo(Point2D), - PutImageData(Rect, IpcBytesReceiver), + PutImageData(ByteBuf, Vector2D, Size2D, Rect), QuadraticCurveTo(Point2D, Point2D), Rect(Rect), RestoreContext, @@ -80,39 +76,34 @@ pub enum Canvas2dMsg { SetShadowColor(RGBA), } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum FromLayoutMsg { SendData(IpcSender), } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum FromScriptMsg { SendPixels(IpcSender>), } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct CanvasGradientStop { pub offset: f64, pub color: RGBA, } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct LinearGradientStyle { pub x0: f64, pub y0: f64, pub x1: f64, pub y1: f64, - pub stops: Vec, + pub stops: Vec } impl LinearGradientStyle { - pub fn new( - x0: f64, - y0: f64, - x1: f64, - y1: f64, - stops: Vec, - ) -> LinearGradientStyle { + pub fn new(x0: f64, y0: f64, x1: f64, y1: f64, stops: Vec) + -> LinearGradientStyle { LinearGradientStyle { x0: x0, y0: y0, @@ -123,7 +114,7 @@ impl LinearGradientStyle { } } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct RadialGradientStyle { pub x0: f64, pub y0: f64, @@ -131,19 +122,12 @@ pub struct RadialGradientStyle { pub x1: f64, pub y1: f64, pub r1: f64, - pub stops: Vec, + pub stops: Vec } impl RadialGradientStyle { - pub fn new( - x0: f64, - y0: f64, - r0: f64, - x1: f64, - y1: f64, - r1: f64, - stops: Vec, - ) -> RadialGradientStyle { + pub fn new(x0: f64, y0: f64, r0: f64, x1: f64, y1: f64, r1: f64, stops: Vec) + -> RadialGradientStyle { RadialGradientStyle { x0: x0, y0: y0, @@ -156,10 +140,10 @@ impl RadialGradientStyle { } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct SurfaceStyle { pub surface_data: ByteBuf, - pub surface_size: Size2D, + pub surface_size: Size2D, pub repeat_x: bool, pub repeat_y: bool, } @@ -167,7 +151,7 @@ pub struct SurfaceStyle { impl SurfaceStyle { pub fn new( surface_data: Vec, - surface_size: Size2D, + surface_size: Size2D, repeat_x: bool, repeat_y: bool, ) -> Self { @@ -180,7 +164,8 @@ impl SurfaceStyle { } } -#[derive(Clone, Debug, Deserialize, Serialize)] + +#[derive(Clone, Deserialize, Serialize)] pub enum FillOrStrokeStyle { Color(RGBA), LinearGradient(LinearGradientStyle), @@ -188,7 +173,7 @@ pub enum FillOrStrokeStyle { Surface(SurfaceStyle), } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum LineCapStyle { Butt = 0, Round = 1, @@ -208,7 +193,7 @@ impl FromStr for LineCapStyle { } } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum LineJoinStyle { Round = 0, Bevel = 1, @@ -228,7 +213,7 @@ impl FromStr for LineJoinStyle { } } -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum RepetitionStyle { Repeat, RepeatX, @@ -250,7 +235,7 @@ impl FromStr for RepetitionStyle { } } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum CompositionStyle { SrcIn, SrcOut, @@ -270,18 +255,18 @@ impl FromStr for CompositionStyle { fn from_str(string: &str) -> Result { match string { - "source-in" => Ok(CompositionStyle::SrcIn), - "source-out" => Ok(CompositionStyle::SrcOut), - "source-over" => Ok(CompositionStyle::SrcOver), - "source-atop" => Ok(CompositionStyle::SrcAtop), - "destination-in" => Ok(CompositionStyle::DestIn), - "destination-out" => Ok(CompositionStyle::DestOut), + "source-in" => Ok(CompositionStyle::SrcIn), + "source-out" => Ok(CompositionStyle::SrcOut), + "source-over" => Ok(CompositionStyle::SrcOver), + "source-atop" => Ok(CompositionStyle::SrcAtop), + "destination-in" => Ok(CompositionStyle::DestIn), + "destination-out" => Ok(CompositionStyle::DestOut), "destination-over" => Ok(CompositionStyle::DestOver), "destination-atop" => Ok(CompositionStyle::DestAtop), - "copy" => Ok(CompositionStyle::Copy), - "lighter" => Ok(CompositionStyle::Lighter), - "xor" => Ok(CompositionStyle::Xor), - _ => Err(()), + "copy" => Ok(CompositionStyle::Copy), + "lighter" => Ok(CompositionStyle::Lighter), + "xor" => Ok(CompositionStyle::Xor), + _ => Err(()) } } } @@ -289,22 +274,22 @@ impl FromStr for CompositionStyle { impl CompositionStyle { pub fn to_str(&self) -> &str { match *self { - CompositionStyle::SrcIn => "source-in", - CompositionStyle::SrcOut => "source-out", - CompositionStyle::SrcOver => "source-over", - CompositionStyle::SrcAtop => "source-atop", - CompositionStyle::DestIn => "destination-in", - CompositionStyle::DestOut => "destination-out", + CompositionStyle::SrcIn => "source-in", + CompositionStyle::SrcOut => "source-out", + CompositionStyle::SrcOver => "source-over", + CompositionStyle::SrcAtop => "source-atop", + CompositionStyle::DestIn => "destination-in", + CompositionStyle::DestOut => "destination-out", CompositionStyle::DestOver => "destination-over", CompositionStyle::DestAtop => "destination-atop", - CompositionStyle::Copy => "copy", - CompositionStyle::Lighter => "lighter", - CompositionStyle::Xor => "xor", + CompositionStyle::Copy => "copy", + CompositionStyle::Lighter => "lighter", + CompositionStyle::Xor => "xor", } } } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum BlendingStyle { Multiply, Screen, @@ -328,22 +313,22 @@ impl FromStr for BlendingStyle { fn from_str(string: &str) -> Result { match string { - "multiply" => Ok(BlendingStyle::Multiply), - "screen" => Ok(BlendingStyle::Screen), - "overlay" => Ok(BlendingStyle::Overlay), - "darken" => Ok(BlendingStyle::Darken), - "lighten" => Ok(BlendingStyle::Lighten), + "multiply" => Ok(BlendingStyle::Multiply), + "screen" => Ok(BlendingStyle::Screen), + "overlay" => Ok(BlendingStyle::Overlay), + "darken" => Ok(BlendingStyle::Darken), + "lighten" => Ok(BlendingStyle::Lighten), "color-dodge" => Ok(BlendingStyle::ColorDodge), - "color-burn" => Ok(BlendingStyle::ColorBurn), - "hard-light" => Ok(BlendingStyle::HardLight), - "soft-light" => Ok(BlendingStyle::SoftLight), - "difference" => Ok(BlendingStyle::Difference), - "exclusion" => Ok(BlendingStyle::Exclusion), - "hue" => Ok(BlendingStyle::Hue), - "saturation" => Ok(BlendingStyle::Saturation), - "color" => Ok(BlendingStyle::Color), - "luminosity" => Ok(BlendingStyle::Luminosity), - _ => Err(()), + "color-burn" => Ok(BlendingStyle::ColorBurn), + "hard-light" => Ok(BlendingStyle::HardLight), + "soft-light" => Ok(BlendingStyle::SoftLight), + "difference" => Ok(BlendingStyle::Difference), + "exclusion" => Ok(BlendingStyle::Exclusion), + "hue" => Ok(BlendingStyle::Hue), + "saturation" => Ok(BlendingStyle::Saturation), + "color" => Ok(BlendingStyle::Color), + "luminosity" => Ok(BlendingStyle::Luminosity), + _ => Err(()) } } } @@ -351,26 +336,26 @@ impl FromStr for BlendingStyle { impl BlendingStyle { pub fn to_str(&self) -> &str { match *self { - BlendingStyle::Multiply => "multiply", - BlendingStyle::Screen => "screen", - BlendingStyle::Overlay => "overlay", - BlendingStyle::Darken => "darken", - BlendingStyle::Lighten => "lighten", + BlendingStyle::Multiply => "multiply", + BlendingStyle::Screen => "screen", + BlendingStyle::Overlay => "overlay", + BlendingStyle::Darken => "darken", + BlendingStyle::Lighten => "lighten", BlendingStyle::ColorDodge => "color-dodge", - BlendingStyle::ColorBurn => "color-burn", - BlendingStyle::HardLight => "hard-light", - BlendingStyle::SoftLight => "soft-light", + BlendingStyle::ColorBurn => "color-burn", + BlendingStyle::HardLight => "hard-light", + BlendingStyle::SoftLight => "soft-light", BlendingStyle::Difference => "difference", - BlendingStyle::Exclusion => "exclusion", - BlendingStyle::Hue => "hue", + BlendingStyle::Exclusion => "exclusion", + BlendingStyle::Hue => "hue", BlendingStyle::Saturation => "saturation", - BlendingStyle::Color => "color", + BlendingStyle::Color => "color", BlendingStyle::Luminosity => "luminosity", } } } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum CompositionOrBlending { Composition(CompositionStyle), Blending(BlendingStyle), @@ -397,3 +382,38 @@ impl FromStr for CompositionOrBlending { Err(()) } } + +// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this. +pub fn byte_swap(data: &mut [u8]) { + let length = data.len(); + // FIXME(rust #27741): Range::step_by is not stable yet as of this writing. + let mut i = 0; + while i < length { + let r = data[i + 2]; + data[i + 2] = data[i + 0]; + data[i + 0] = r; + i += 4; + } +} + +pub fn multiply_u8_pixel(a: u8, b: u8) -> u8 { + return (a as u32 * b as u32 / 255) as u8; +} + +pub fn byte_swap_and_premultiply(data: &mut [u8]) { + let length = data.len(); + + let mut i = 0; + while i < length { + let r = data[i + 2]; + let g = data[i + 1]; + let b = data[i + 0]; + let a = data[i + 3]; + + data[i + 0] = multiply_u8_pixel(r, a); + data[i + 1] = multiply_u8_pixel(g, a); + data[i + 2] = multiply_u8_pixel(b, a); + + i += 4; + } +} diff --git a/components/canvas_traits/lib.rs b/components/canvas_traits/lib.rs index 2e11d1704c66..b2147d880e6c 100644 --- a/components/canvas_traits/lib.rs +++ b/components/canvas_traits/lib.rs @@ -4,14 +4,21 @@ #![crate_name = "canvas_traits"] #![crate_type = "rlib"] + #![deny(unsafe_code)] -#[macro_use] -extern crate lazy_static; -#[macro_use] -extern crate malloc_size_of_derive; -#[macro_use] -extern crate serde; +extern crate cssparser; +extern crate euclid; +extern crate gleam; +extern crate ipc_channel; +#[macro_use] extern crate lazy_static; +extern crate malloc_size_of; +#[macro_use] extern crate malloc_size_of_derive; +extern crate offscreen_gl_context; +#[macro_use] extern crate serde; +extern crate serde_bytes; +extern crate servo_config; +extern crate webrender_api; pub mod canvas; pub mod webgl; diff --git a/components/canvas_traits/webgl.rs b/components/canvas_traits/webgl.rs index dce9c441e1ca..ad10ed7edd0f 100644 --- a/components/canvas_traits/webgl.rs +++ b/components/canvas_traits/webgl.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use euclid::{Rect, Size2D}; +use euclid::Size2D; use gleam::gl; use ipc_channel::ipc::{IpcBytesReceiver, IpcBytesSender}; use offscreen_gl_context::{GLContextAttributes, GLLimits}; @@ -11,20 +11,20 @@ use std::borrow::Cow; use std::num::NonZeroU32; use webrender_api::{DocumentId, ImageKey, PipelineId}; -/// Helper function that creates a WebGL channel (WebGLSender, WebGLReceiver) to be used in WebGLCommands. -pub use crate::webgl_channel::webgl_channel; -/// Entry point channel type used for sending WebGLMsg messages to the WebGL renderer. -pub use crate::webgl_channel::WebGLChan; -/// Entry point type used in a Script Pipeline to get the WebGLChan to be used in that thread. -pub use crate::webgl_channel::WebGLPipeline; +/// Sender type used in WebGLCommands. +pub use ::webgl_channel::WebGLSender; /// Receiver type used in WebGLCommands. -pub use crate::webgl_channel::WebGLReceiver; +pub use ::webgl_channel::WebGLReceiver; /// Result type for send()/recv() calls in in WebGLCommands. -pub use crate::webgl_channel::WebGLSendResult; -/// Sender type used in WebGLCommands. -pub use crate::webgl_channel::WebGLSender; +pub use ::webgl_channel::WebGLSendResult; +/// Helper function that creates a WebGL channel (WebGLSender, WebGLReceiver) to be used in WebGLCommands. +pub use ::webgl_channel::webgl_channel; +/// Entry point type used in a Script Pipeline to get the WebGLChan to be used in that thread. +pub use ::webgl_channel::WebGLPipeline; +/// Entry point channel type used for sending WebGLMsg messages to the WebGL renderer. +pub use ::webgl_channel::WebGLChan; -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct WebGLCommandBacktrace { #[cfg(feature = "webgl_backtrace")] pub backtrace: String, @@ -33,17 +33,13 @@ pub struct WebGLCommandBacktrace { } /// WebGL Message API -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum WebGLMsg { /// Creates a new WebGLContext. - CreateContext( - WebGLVersion, - Size2D, - GLContextAttributes, - WebGLSender>, - ), + CreateContext(WebGLVersion, Size2D, GLContextAttributes, + WebGLSender>), /// Resizes a WebGLContext. - ResizeContext(WebGLContextId, Size2D, WebGLSender>), + ResizeContext(WebGLContextId, Size2D, WebGLSender>), /// Drops a WebGLContext. RemoveContext(WebGLContextId), /// Runs a WebGLCommand in a specific WebGLContext. @@ -70,7 +66,7 @@ pub enum WebGLMsg { } /// Contains the WebGLCommand sender and information about a WebGLContext -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct WebGLCreateContextResult { /// Sender instance to send commands to the specific WebGLContext pub sender: WebGLMsgSender, @@ -82,7 +78,7 @@ pub struct WebGLCreateContextResult { pub glsl_version: WebGLSLVersion, } -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, Serialize)] pub enum WebGLContextShareMode { /// Fast: a shared texture_id is used in WebRender. SharedTexture, @@ -91,7 +87,7 @@ pub enum WebGLContextShareMode { } /// Defines the WebGL version -#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] pub enum WebGLVersion { /// https://www.khronos.org/registry/webgl/specs/1.0.2/ /// Conforms closely to the OpenGL ES 2.0 API @@ -102,7 +98,7 @@ pub enum WebGLVersion { } /// Defines the GLSL version supported by the WebGL backend contexts. -#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] pub struct WebGLSLVersion { /// Major GLSL version pub major: u32, @@ -111,7 +107,7 @@ pub struct WebGLSLVersion { } /// Helper struct to send WebGLCommands to a specific WebGLContext. -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct WebGLMsgSender { ctx_id: WebGLContextId, #[ignore_malloc_size_of = "channels are hard"] @@ -134,26 +130,22 @@ impl WebGLMsgSender { /// Send a WebGLCommand message #[inline] pub fn send(&self, command: WebGLCommand, backtrace: WebGLCommandBacktrace) -> WebGLSendResult { - self.sender - .send(WebGLMsg::WebGLCommand(self.ctx_id, command, backtrace)) + self.sender.send(WebGLMsg::WebGLCommand(self.ctx_id, command, backtrace)) } /// Send a WebVRCommand message #[inline] pub fn send_vr(&self, command: WebVRCommand) -> WebGLSendResult { - self.sender - .send(WebGLMsg::WebVRCommand(self.ctx_id, command)) + self.sender.send(WebGLMsg::WebVRCommand(self.ctx_id, command)) } /// Send a resize message #[inline] - pub fn send_resize( - &self, - size: Size2D, - sender: WebGLSender>, - ) -> WebGLSendResult { - self.sender - .send(WebGLMsg::ResizeContext(self.ctx_id, size, sender)) + pub fn send_resize(&self, + size: Size2D, + sender: WebGLSender>) + -> WebGLSendResult { + self.sender.send(WebGLMsg::ResizeContext(self.ctx_id, size, sender)) } #[inline] @@ -163,8 +155,7 @@ impl WebGLMsgSender { #[inline] pub fn send_update_wr_image(&self, sender: WebGLSender) -> WebGLSendResult { - self.sender - .send(WebGLMsg::UpdateWebRenderImage(self.ctx_id, sender)) + self.sender.send(WebGLMsg::UpdateWebRenderImage(self.ctx_id, sender)) } pub fn send_dom_to_texture(&self, command: DOMToTextureCommand) -> WebGLSendResult { @@ -231,9 +222,9 @@ pub enum WebGLCommand { GetRenderbufferParameter(u32, u32, WebGLSender), PolygonOffset(f32, f32), RenderbufferStorage(u32, u32, i32, i32), - ReadPixels(Rect, u32, u32, IpcBytesSender), + ReadPixels(i32, i32, i32, i32, u32, u32, IpcBytesSender), SampleCoverage(f32, bool), - Scissor(i32, i32, u32, u32), + Scissor(i32, i32, i32, i32), StencilFunc(u32, i32, u32), StencilFuncSeparate(u32, u32, i32, u32), StencilMask(u32), @@ -294,34 +285,11 @@ pub enum WebGLCommand { GetTexParameterInt(u32, TexParameterInt, WebGLSender), TexParameteri(u32, u32, i32), TexParameterf(u32, u32, f32), - DrawArrays { - mode: u32, - first: i32, - count: i32, - }, - DrawArraysInstanced { - mode: u32, - first: i32, - count: i32, - primcount: i32, - }, - DrawElements { - mode: u32, - count: i32, - type_: u32, - offset: u32, - }, - DrawElementsInstanced { - mode: u32, - count: i32, - type_: u32, - offset: u32, - primcount: i32, - }, - VertexAttribDivisor { - index: u32, - divisor: u32, - }, + DrawArrays { mode: u32, first: i32, count: i32 }, + DrawArraysInstanced { mode: u32, first: i32, count: i32, primcount: i32 }, + DrawElements { mode: u32, count: i32, type_: u32, offset: u32 }, + DrawElementsInstanced { mode: u32, count: i32, type_: u32, offset: u32, primcount: i32 }, + VertexAttribDivisor { index: u32, divisor: u32 }, GetUniformBool(WebGLProgramId, i32, WebGLSender), GetUniformBool2(WebGLProgramId, i32, WebGLSender<[bool; 2]>), GetUniformBool3(WebGLProgramId, i32, WebGLSender<[bool; 3]>), @@ -336,11 +304,7 @@ pub enum WebGLCommand { GetUniformFloat4(WebGLProgramId, i32, WebGLSender<[f32; 4]>), GetUniformFloat9(WebGLProgramId, i32, WebGLSender<[f32; 9]>), GetUniformFloat16(WebGLProgramId, i32, WebGLSender<[f32; 16]>), - InitializeFramebuffer { - color: bool, - depth: bool, - stencil: bool, - }, + InitializeFramebuffer { color: bool, depth: bool, stencil: bool }, } macro_rules! define_resource_id_struct { @@ -360,6 +324,7 @@ macro_rules! define_resource_id_struct { self.0.get() } } + }; } @@ -370,10 +335,9 @@ macro_rules! define_resource_id { #[allow(unsafe_code)] impl<'de> ::serde::Deserialize<'de> for $name { fn deserialize(deserializer: D) -> Result - where - D: ::serde::Deserializer<'de>, + where D: ::serde::Deserializer<'de> { - let id = u32::deserialize(deserializer)?; + let id = try!(u32::deserialize(deserializer)); if id == 0 { Err(::serde::de::Error::custom("expected a non-zero value")) } else { @@ -384,33 +348,32 @@ macro_rules! define_resource_id { impl ::serde::Serialize for $name { fn serialize(&self, serializer: S) -> Result - where - S: ::serde::Serializer, + where S: ::serde::Serializer { self.get().serialize(serializer) } } impl ::std::fmt::Debug for $name { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) + -> Result<(), ::std::fmt::Error> { fmt.debug_tuple(stringify!($name)) - .field(&self.get()) - .finish() + .field(&self.get()) + .finish() } } impl ::std::fmt::Display for $name { - fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> Result<(), ::std::fmt::Error> { + fn fmt(&self, fmt: &mut ::std::fmt::Formatter) + -> Result<(), ::std::fmt::Error> { write!(fmt, "{}", self.get()) } } impl ::malloc_size_of::MallocSizeOf for $name { - fn size_of(&self, _ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize { - 0 - } + fn size_of(&self, _ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize { 0 } } - }; + } } define_resource_id!(WebGLBufferId); @@ -421,9 +384,8 @@ define_resource_id!(WebGLProgramId); define_resource_id!(WebGLShaderId); define_resource_id!(WebGLVertexArrayId); -#[derive( - Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord, PartialEq, PartialOrd, Serialize, -)] +#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, MallocSizeOf, Ord)] +#[derive(PartialEq, PartialOrd, Serialize)] pub struct WebGLContextId(pub usize); #[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] @@ -447,7 +409,7 @@ pub type WebGLResult = Result; pub type WebVRDeviceId = u32; // WebVR commands that must be called in the WebGL render thread. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum WebVRCommand { /// Start presenting to a VR device. Create(WebVRDeviceId), @@ -456,7 +418,7 @@ pub enum WebVRCommand { /// Submit the frame to a VR device using the specified texture coordinates. SubmitFrame(WebVRDeviceId, [f32; 4], [f32; 4]), /// Stop presenting to a VR device - Release(WebVRDeviceId), + Release(WebVRDeviceId) } // Trait object that handles WebVR commands. @@ -466,16 +428,10 @@ pub trait WebVRRenderHandler: Send { } /// WebGL commands required to implement DOMToTexture feature. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum DOMToTextureCommand { /// Attaches a HTMLIFrameElement to a WebGLTexture. - Attach( - WebGLContextId, - WebGLTextureId, - DocumentId, - PipelineId, - Size2D, - ), + Attach(WebGLContextId, WebGLTextureId, DocumentId, PipelineId, Size2D), /// Releases the HTMLIFrameElement to WebGLTexture attachment. Detach(WebGLTextureId), /// Lock message used for a correct synchronization with WebRender GL flow. @@ -483,7 +439,7 @@ pub enum DOMToTextureCommand { } /// Information about a WebGL program linking operation. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ProgramLinkInfo { /// Whether the program was linked successfully. pub linked: bool, @@ -494,7 +450,7 @@ pub struct ProgramLinkInfo { } /// Description of a single active attribute. -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct ActiveAttribInfo { /// The name of the attribute. pub name: String, @@ -507,7 +463,7 @@ pub struct ActiveAttribInfo { } /// Description of a single active uniform. -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct ActiveUniformInfo { /// The base name of the uniform. pub base_name: Box, @@ -644,9 +600,3 @@ parameters! { }), } } - -pub fn is_gles() -> bool { - // TODO: align this with the actual kind of graphics context in use, rather than - // making assumptions based on platform - cfg!(any(target_os = "android", target_os = "ios")) -} diff --git a/components/canvas_traits/webgl_channel/ipc.rs b/components/canvas_traits/webgl_channel/ipc.rs index 28c6c81816f9..a00ceda75ed3 100644 --- a/components/canvas_traits/webgl_channel/ipc.rs +++ b/components/canvas_traits/webgl_channel/ipc.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use ipc_channel; use serde::{Deserialize, Serialize}; use std::io; diff --git a/components/canvas_traits/webgl_channel/mod.rs b/components/canvas_traits/webgl_channel/mod.rs index cd8accb6e153..3c6bd1690b0d 100644 --- a/components/canvas_traits/webgl_channel/mod.rs +++ b/components/canvas_traits/webgl_channel/mod.rs @@ -7,7 +7,7 @@ mod ipc; mod mpsc; -use crate::webgl::WebGLMsg; +use ::webgl::WebGLMsg; use serde::{Deserialize, Serialize}; use servo_config::opts; use std::fmt; @@ -85,7 +85,7 @@ where } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct WebGLChan(pub WebGLSender); impl WebGLChan { @@ -95,7 +95,7 @@ impl WebGLChan { } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct WebGLPipeline(pub WebGLChan); impl WebGLPipeline { diff --git a/components/channel/Cargo.toml b/components/channel/Cargo.toml index 5b30d622830f..0eb5655eaaa0 100644 --- a/components/channel/Cargo.toml +++ b/components/channel/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_channel" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/channel/lib.rs b/components/channel/lib.rs index d8f637b99dbc..87950fbe22ab 100644 --- a/components/channel/lib.rs +++ b/components/channel/lib.rs @@ -2,6 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate crossbeam_channel; +extern crate ipc_channel; +extern crate serde; + pub mod base_channel { pub use crossbeam_channel::*; } @@ -11,45 +15,46 @@ pub use crossbeam_channel::*; use ipc_channel::ipc::IpcReceiver; use ipc_channel::router::ROUTER; use serde::{Deserialize, Serialize}; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + pub fn route_ipc_receiver_to_new_servo_receiver(ipc_receiver: IpcReceiver) -> Receiver where - T: for<'de> Deserialize<'de> + Serialize + Send + 'static, + T: for<'de> Deserialize<'de> + Serialize + Send + 'static { let (servo_sender, servo_receiver) = channel(); ROUTER.add_route( ipc_receiver.to_opaque(), - Box::new(move |message| drop(servo_sender.send(message.to::().unwrap()))), + Box::new(move |message| { + drop(servo_sender.send(message.to::().unwrap())) + }), ); servo_receiver } -pub fn route_ipc_receiver_to_new_servo_sender( - ipc_receiver: IpcReceiver, - servo_sender: Sender, -) where - T: for<'de> Deserialize<'de> + Serialize + Send + 'static, +pub fn route_ipc_receiver_to_new_servo_sender(ipc_receiver: IpcReceiver, servo_sender: Sender) +where + T: for<'de> Deserialize<'de> + Serialize + Send + 'static { ROUTER.add_route( ipc_receiver.to_opaque(), - Box::new(move |message| drop(servo_sender.send(message.to::().unwrap()))), + Box::new(move |message| { + drop(servo_sender.send(message.to::().unwrap())) + }), ) } pub fn channel() -> (Sender, Receiver) { let (base_sender, base_receiver) = crossbeam_channel::unbounded::(); let is_disconnected = Arc::new(AtomicBool::new(false)); - ( - Sender::new(base_sender, is_disconnected.clone()), - Receiver::new(base_receiver, is_disconnected), - ) + (Sender::new(base_sender, is_disconnected.clone()), + Receiver::new(base_receiver, is_disconnected)) } #[derive(Debug, PartialEq)] pub enum ChannelError { - ChannelClosedError, + ChannelClosedError } pub struct Receiver { @@ -73,10 +78,7 @@ impl Clone for Receiver { } impl Receiver { - pub fn new( - receiver: crossbeam_channel::Receiver, - is_disconnected: Arc, - ) -> Receiver { + pub fn new(receiver: crossbeam_channel::Receiver, is_disconnected: Arc) -> Receiver { Receiver { receiver, is_disconnected, @@ -132,10 +134,7 @@ impl Clone for Sender { } impl Sender { - pub fn new( - sender: crossbeam_channel::Sender, - is_disconnected: Arc, - ) -> Sender { + pub fn new(sender: crossbeam_channel::Sender, is_disconnected: Arc) -> Sender { Sender { sender, is_disconnected, diff --git a/components/compositing/Cargo.toml b/components/compositing/Cargo.toml index ed991671c9f6..3f2096d9557c 100644 --- a/components/compositing/Cargo.toml +++ b/components/compositing/Cargo.toml @@ -3,7 +3,6 @@ name = "compositing" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false build = "build.rs" @@ -22,7 +21,6 @@ gleam = {version = "0.6", optional = true} image = "0.19" ipc-channel = "0.11" libc = "0.2" -keyboard-types = {version = "0.4.2-servo", features = ["serde"]} log = "0.4" msg = {path = "../msg"} net_traits = {path = "../net_traits"} @@ -39,3 +37,6 @@ webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} [build-dependencies] toml = "0.4.5" + +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"]} diff --git a/components/compositing/build.rs b/components/compositing/build.rs index 9803ce9480de..8a13f9632d73 100644 --- a/components/compositing/build.rs +++ b/components/compositing/build.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate toml; + use std::env; use std::fs::File; use std::io::{Read, Write}; @@ -34,8 +36,7 @@ fn main() { .find(|pkg| { pkg.get("name").and_then(|name| name.as_str()).unwrap_or("") == "webrender" - }) - .and_then(|pkg| pkg.get("source").and_then(|source| source.as_str())) + }).and_then(|pkg| pkg.get("source").and_then(|source| source.as_str())) .unwrap_or("unknown"); let parsed: Vec<&str> = source.split("#").collect(); diff --git a/components/compositing/compositor.rs b/components/compositing/compositor.rs index ee25a835d7e2..ae505c935d5c 100644 --- a/components/compositing/compositor.rs +++ b/components/compositing/compositor.rs @@ -2,19 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::compositor_thread::{CompositorProxy, CompositorReceiver}; -use crate::compositor_thread::{InitialCompositorState, Msg}; -#[cfg(feature = "gleam")] -use crate::gl; -use crate::touch::{TouchAction, TouchHandler}; -use crate::windowing::{ - self, EmbedderCoordinates, MouseWindowEvent, WebRenderDebugOption, WindowMethods, -}; -use crate::CompositionPipeline; -use crate::SendableFrameTree; -use euclid::{TypedPoint2D, TypedScale, TypedVector2D}; +use CompositionPipeline; +use SendableFrameTree; +use compositor_thread::{CompositorProxy, CompositorReceiver}; +use compositor_thread::{InitialCompositorState, Msg}; +use euclid::{TypedPoint2D, TypedVector2D, TypedScale}; use gfx_traits::Epoch; #[cfg(feature = "gleam")] +use gl; +#[cfg(feature = "gleam")] use image::{DynamicImage, ImageFormat}; use ipc_channel::ipc; use libc::c_void; @@ -22,26 +18,30 @@ use msg::constellation_msg::{PipelineId, PipelineIndex, PipelineNamespaceId}; use net_traits::image::base::Image; #[cfg(feature = "gleam")] use net_traits::image::base::PixelFormat; -use profile_traits::time::{self as profile_time, profile, ProfilerCategory}; -use script_traits::CompositorEvent::{MouseButtonEvent, MouseMoveEvent, TouchEvent}; +use profile_traits::time::{self, ProfilerCategory, profile}; use script_traits::{AnimationState, AnimationTickType, ConstellationMsg, LayoutControlMsg}; use script_traits::{MouseButton, MouseEventType, ScrollState, TouchEventType, TouchId}; use script_traits::{UntrustedNodeAddress, WindowSizeData, WindowSizeType}; +use script_traits::CompositorEvent::{MouseMoveEvent, MouseButtonEvent, TouchEvent}; use servo_channel::Sender; use servo_config::opts; use servo_geometry::DeviceIndependentPixel; use std::collections::HashMap; use std::env; -use std::fs::{create_dir_all, File}; +use std::fs::{File, create_dir_all}; use std::io::Write; use std::num::NonZeroU32; use std::rc::Rc; +use std::time::Instant; +use style_traits::{CSSPixel, DevicePixel, PinchZoomFactor}; use style_traits::cursor::CursorKind; use style_traits::viewport::ViewportConstraints; -use style_traits::{CSSPixel, DevicePixel, PinchZoomFactor}; use time::{now, precise_time_ns, precise_time_s}; +use touch::{TouchHandler, TouchAction}; +use webrender; use webrender_api::{self, DeviceIntPoint, DevicePoint, HitTestFlags, HitTestResult}; use webrender_api::{LayoutVector2D, ScrollLocation}; +use windowing::{self, EmbedderCoordinates, MouseWindowEvent, WebRenderDebugOption, WindowMethods}; #[derive(Debug, PartialEq)] enum UnableToComposite { @@ -151,7 +151,7 @@ pub struct IOCompositor { constellation_chan: Sender, /// The channel on which messages can be sent to the time profiler. - time_profiler_chan: profile_time::ProfilerChan, + time_profiler_chan: time::ProfilerChan, /// Touch input state machine touch_handler: TouchHandler, @@ -166,6 +166,11 @@ pub struct IOCompositor { /// image for the reftest framework. ready_to_save_state: ReadyState, + /// Whether a scroll is in progress; i.e. whether the user's fingers are down. + scroll_in_progress: bool, + + in_scroll_transaction: Option, + /// The webrender renderer. webrender: webrender::Renderer, @@ -262,7 +267,7 @@ impl RenderNotifier { } impl webrender_api::RenderNotifier for RenderNotifier { - fn clone(&self) -> Box { + fn clone(&self) -> Box { Box::new(RenderNotifier::new(self.compositor_proxy.clone())) } @@ -318,6 +323,8 @@ impl IOCompositor { time_profiler_chan: state.time_profiler_chan, last_composite_time: 0, ready_to_save_state: ReadyState::Unknown, + scroll_in_progress: false, + in_scroll_transaction: None, webrender: state.webrender, webrender_document: state.webrender_document, webrender_api: state.webrender_api, @@ -367,7 +374,7 @@ impl IOCompositor { // Tell the profiler, memory profiler, and scrolling timer to shut down. if let Ok((sender, receiver)) = ipc::channel() { self.time_profiler_chan - .send(profile_time::ProfilerMsg::Exit(sender)); + .send(time::ProfilerMsg::Exit(sender)); let _ = receiver.recv(); } @@ -499,10 +506,7 @@ impl IOCompositor { (Msg::GetScreenAvailSize(req), ShutdownState::NotShuttingDown) => { if let Err(e) = req.send(self.embedder_coordinates.screen_avail) { - warn!( - "Sending response to get screen avail size failed ({:?}).", - e - ); + warn!("Sending response to get screen avail size failed ({:?}).", e); } }, @@ -848,15 +852,44 @@ impl IOCompositor { match phase { TouchEventType::Move => self.on_scroll_window_event(delta, cursor), TouchEventType::Up | TouchEventType::Cancel => { - self.on_scroll_window_event(delta, cursor); + self.on_scroll_end_window_event(delta, cursor); }, TouchEventType::Down => { - self.on_scroll_window_event(delta, cursor); + self.on_scroll_start_window_event(delta, cursor); }, } } fn on_scroll_window_event(&mut self, scroll_location: ScrollLocation, cursor: DeviceIntPoint) { + self.in_scroll_transaction = Some(Instant::now()); + self.pending_scroll_zoom_events.push(ScrollZoomEvent { + magnification: 1.0, + scroll_location: scroll_location, + cursor: cursor, + event_count: 1, + }); + } + + fn on_scroll_start_window_event( + &mut self, + scroll_location: ScrollLocation, + cursor: DeviceIntPoint, + ) { + self.scroll_in_progress = true; + self.pending_scroll_zoom_events.push(ScrollZoomEvent { + magnification: 1.0, + scroll_location: scroll_location, + cursor: cursor, + event_count: 1, + }); + } + + fn on_scroll_end_window_event( + &mut self, + scroll_location: ScrollLocation, + cursor: DeviceIntPoint, + ) { + self.scroll_in_progress = false; self.pending_scroll_zoom_events.push(ScrollZoomEvent { magnification: 1.0, scroll_location: scroll_location, @@ -1155,19 +1188,15 @@ impl IOCompositor { pub fn composite(&mut self) { let target = self.composite_target; match self.composite_specific_target(target) { - Ok(_) => { - if opts::get().output_file.is_some() || opts::get().exit_after_load { - println!("Shutting down the Constellation after generating an output file or exit flag specified"); - self.start_shutting_down(); - } + Ok(_) => if opts::get().output_file.is_some() || opts::get().exit_after_load { + println!("Shutting down the Constellation after generating an output file or exit flag specified"); + self.start_shutting_down(); }, - Err(e) => { - if opts::get().is_running_problem_test { - if e != UnableToComposite::NotReadyToPaintImage( - NotReadyToPaint::WaitingOnConstellation, - ) { - println!("not ready to composite: {:?}", e); - } + Err(e) => if opts::get().is_running_problem_test { + if e != UnableToComposite::NotReadyToPaintImage( + NotReadyToPaint::WaitingOnConstellation, + ) { + println!("not ready to composite: {:?}", e); } }, } @@ -1184,7 +1213,7 @@ impl IOCompositor { ) -> Result, UnableToComposite> { let width = self.embedder_coordinates.framebuffer.width_typed(); let height = self.embedder_coordinates.framebuffer.height_typed(); - if !self.window.prepare_for_composite() { + if !self.window.prepare_for_composite(width, height) { return Err(UnableToComposite::WindowUnprepared); } @@ -1259,7 +1288,7 @@ impl IOCompositor { if let Some(pipeline) = self.pipeline(*id) { // and inform the layout thread with the measured paint time. let msg = LayoutControlMsg::PaintMetric(epoch, paint_time); - if let Err(e) = pipeline.layout_chan.send(msg) { + if let Err(e) = pipeline.layout_chan.send(msg) { warn!("Sending PaintMetric message to layout failed ({:?}).", e); } } @@ -1449,8 +1478,7 @@ impl IOCompositor { val.as_ref() .map(|dir| dir.join("capture_webrender").join(&capture_id)) .ok() - }) - .find(|val| match create_dir_all(&val) { + }).find(|val| match create_dir_all(&val) { Ok(_) => true, Err(err) => { eprintln!("Unable to create path '{:?}' for capture: {:?}", &val, err); diff --git a/components/compositing/compositor_thread.rs b/components/compositing/compositor_thread.rs index 76b14d3eb6e0..c0a0169cdcd6 100644 --- a/components/compositing/compositor_thread.rs +++ b/components/compositing/compositor_thread.rs @@ -4,8 +4,8 @@ //! Communication with the compositor thread. -use crate::compositor::CompositingReason; -use crate::SendableFrameTree; +use SendableFrameTree; +use compositor::CompositingReason; use embedder_traits::EventLoopWaker; use gfx_traits::Epoch; use ipc_channel::ipc::IpcSender; @@ -17,12 +17,13 @@ use script_traits::{AnimationState, ConstellationMsg, EventResult}; use servo_channel::{Receiver, Sender}; use std::fmt::{Debug, Error, Formatter}; use style_traits::viewport::ViewportConstraints; +use webrender; use webrender_api::{self, DeviceIntPoint, DeviceUintSize}; /// Sends messages to the compositor. pub struct CompositorProxy { pub sender: Sender, - pub event_loop_waker: Box, + pub event_loop_waker: Box, } impl CompositorProxy { @@ -97,7 +98,7 @@ pub enum Msg { /// Runs a closure in the compositor thread. /// It's used to dispatch functions from webrender to the main thread's event loop. /// Required to allow WGL GLContext sharing in Windows. - Dispatch(Box), + Dispatch(Box), /// Indicates to the compositor that it needs to record the time when the frame with /// the given ID (epoch) is painted and report it to the layout thread of the given /// pipeline ID. diff --git a/components/compositing/gl.rs b/components/compositing/gl.rs index 59c1225cd914..6637ef203eaa 100644 --- a/components/compositing/gl.rs +++ b/components/compositing/gl.rs @@ -14,7 +14,7 @@ pub struct RenderTargetInfo { } pub fn initialize_png( - gl: &dyn gl::Gl, + gl: &gl::Gl, width: DeviceUintLength, height: DeviceUintLength, ) -> RenderTargetInfo { @@ -80,7 +80,7 @@ pub fn initialize_png( } pub fn draw_img( - gl: &dyn gl::Gl, + gl: &gl::Gl, render_target_info: RenderTargetInfo, width: DeviceUintLength, height: DeviceUintLength, diff --git a/components/compositing/lib.rs b/components/compositing/lib.rs index d54feac56bb7..6b8bfb5aaf7a 100644 --- a/components/compositing/lib.rs +++ b/components/compositing/lib.rs @@ -4,13 +4,34 @@ #![deny(unsafe_code)] +extern crate embedder_traits; +extern crate euclid; +extern crate gfx_traits; +#[cfg(feature = "gleam")] +extern crate gleam; +#[cfg(feature = "gleam")] +extern crate image; +extern crate ipc_channel; +extern crate libc; #[macro_use] extern crate log; +extern crate msg; +extern crate net_traits; +extern crate profile_traits; +extern crate script_traits; +extern crate servo_channel; +extern crate servo_config; +extern crate servo_geometry; +extern crate servo_url; +extern crate style_traits; +extern crate time; +extern crate webrender; +extern crate webrender_api; -pub use crate::compositor::IOCompositor; -pub use crate::compositor::RenderNotifier; -pub use crate::compositor::ShutdownState; -pub use crate::compositor_thread::CompositorProxy; +pub use compositor_thread::CompositorProxy; +pub use compositor::IOCompositor; +pub use compositor::RenderNotifier; +pub use compositor::ShutdownState; use euclid::TypedSize2D; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; diff --git a/components/compositing/touch.rs b/components/compositing/touch.rs index 227758ddd113..28a2588a91f4 100644 --- a/components/compositing/touch.rs +++ b/components/compositing/touch.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use self::TouchState::*; -use euclid::TypedScale; use euclid::{TypedPoint2D, TypedVector2D}; +use euclid::TypedScale; use script_traits::{EventResult, TouchId}; +use self::TouchState::*; use style_traits::DevicePixel; /// Minimum number of `DeviceIndependentPixel` to begin touch scrolling. diff --git a/components/compositing/windowing.rs b/components/compositing/windowing.rs index 087062c3fc2b..2e773e37aa7e 100644 --- a/components/compositing/windowing.rs +++ b/components/compositing/windowing.rs @@ -8,16 +8,15 @@ use embedder_traits::EventLoopWaker; use euclid::TypedScale; #[cfg(feature = "gleam")] use gleam::gl; -use keyboard_types::KeyboardEvent; -use msg::constellation_msg::{TopLevelBrowsingContextId, TraversalDirection}; +use msg::constellation_msg::{Key, KeyModifiers, KeyState, TopLevelBrowsingContextId, TraversalDirection}; use script_traits::{MouseButton, TouchEventType, TouchId}; -use servo_geometry::DeviceIndependentPixel; +use servo_geometry::{DeviceIndependentPixel, DeviceUintLength}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; #[cfg(feature = "gleam")] use std::rc::Rc; use style_traits::DevicePixel; -use webrender_api::{DeviceIntPoint, DevicePoint, DeviceUintRect, DeviceUintSize, ScrollLocation}; +use webrender_api::{DeviceIntPoint, DevicePoint, DeviceUintSize, DeviceUintRect, ScrollLocation}; #[derive(Clone)] pub enum MouseWindowEvent { @@ -71,7 +70,7 @@ pub enum WindowEvent { /// Sent when the user quits the application Quit, /// Sent when a key input state changes - Keyboard(KeyboardEvent), + KeyEvent(Option, Key, KeyState, KeyModifiers), /// Sent when Ctr+R/Apple+R is called to reload the current page. Reload(TopLevelBrowsingContextId), /// Create a new top level browsing context @@ -95,7 +94,7 @@ impl Debug for WindowEvent { WindowEvent::Idle => write!(f, "Idle"), WindowEvent::Refresh => write!(f, "Refresh"), WindowEvent::Resize => write!(f, "Resize"), - WindowEvent::Keyboard(..) => write!(f, "Keyboard"), + WindowEvent::KeyEvent(..) => write!(f, "Key"), WindowEvent::LoadUrl(..) => write!(f, "LoadUrl"), WindowEvent::MouseWindowEventClass(..) => write!(f, "Mouse"), WindowEvent::MouseWindowMoveEventClass(..) => write!(f, "MouseMove"), @@ -129,12 +128,12 @@ pub trait WindowMethods { /// Requests that the window system prepare a composite. Typically this will involve making /// some type of platform-specific graphics context current. Returns true if the composite may /// proceed and false if it should not. - fn prepare_for_composite(&self) -> bool; + fn prepare_for_composite(&self, width: DeviceUintLength, height: DeviceUintLength) -> bool; /// Return the GL function pointer trait. #[cfg(feature = "gleam")] - fn gl(&self) -> Rc; + fn gl(&self) -> Rc; /// Returns a thread-safe object to wake up the window's event loop. - fn create_event_loop_waker(&self) -> Box; + fn create_event_loop_waker(&self) -> Box; /// Get the coordinates of the native window, the screen and the framebuffer. fn get_coordinates(&self) -> EmbedderCoordinates; /// Set whether the application is currently animating. diff --git a/components/config/Cargo.toml b/components/config/Cargo.toml index 8f49daba0e38..60878c67b484 100644 --- a/components/config/Cargo.toml +++ b/components/config/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_config" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -19,15 +18,15 @@ getopts = "0.2.11" lazy_static = "1" log = "0.4" num_cpus = "1.1.0" +rustc-serialize = "0.3" serde = "1.0" -serde_json = "1.0" servo_geometry = {path = "../geometry"} servo_url = {path = "../url"} url = "1.2" [dev-dependencies] env_logger = "0.5" -std_test_override = { path = "../std_test_override" } +embedder_traits = { path = "../embedder_traits", features = ["tests"] } [target.'cfg(not(target_os = "android"))'.dependencies] dirs = "1.0" diff --git a/components/config/lib.rs b/components/config/lib.rs index d7baff3a71d2..d1a63520f114 100644 --- a/components/config/lib.rs +++ b/components/config/lib.rs @@ -4,12 +4,22 @@ #![deny(unsafe_code)] +#[cfg(not(target_os = "android"))] +extern crate dirs; +extern crate embedder_traits; +extern crate euclid; +extern crate getopts; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; +extern crate num_cpus; +extern crate rustc_serialize; #[macro_use] extern crate serde; +extern crate servo_geometry; +extern crate servo_url; +extern crate url; pub mod basedir; #[allow(unsafe_code)] diff --git a/components/config/opts.rs b/components/config/opts.rs index b542dbb74cc9..293a5f64c101 100644 --- a/components/config/opts.rs +++ b/components/config/opts.rs @@ -5,9 +5,10 @@ //! Configuration options for a single run of the servo application. Created //! from command line arguments. -use crate::prefs::{self, PrefValue, PREFS}; use euclid::TypedSize2D; use getopts::Options; +use num_cpus; +use prefs::{self, PrefValue, PREFS}; use servo_geometry::DeviceIndependentPixel; use servo_url::ServoUrl; use std::borrow::Cow; @@ -18,11 +19,11 @@ use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; -use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; +use std::sync::atomic::{AtomicBool, ATOMIC_BOOL_INIT, Ordering}; use url::{self, Url}; /// Global flags for Servo, currently set on the command line. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct Opts { pub is_running_problem_test: bool, @@ -225,9 +226,6 @@ pub struct Opts { /// Print Progressive Web Metrics to console. pub print_pwm: bool, - - /// Only shutdown once all theads are finished. - pub clean_shutdown: bool, } fn print_usage(app: &str, opts: &Options) { @@ -476,7 +474,7 @@ fn print_debug_usage(app: &str) -> ! { process::exit(0) } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum OutputOptions { /// Database connection config (hostname, name, user, pass) DB(ServoUrl, Option, Option, Option), @@ -506,28 +504,28 @@ enum UserAgent { fn default_user_agent_string(agent: UserAgent) -> &'static str { #[cfg(all(target_os = "linux", target_arch = "x86_64"))] const DESKTOP_UA_STRING: &'static str = - "Mozilla/5.0 (X11; Linux x86_64; rv:63.0) Servo/1.0 Firefox/63.0"; + "Mozilla/5.0 (X11; Linux x86_64; rv:55.0) Servo/1.0 Firefox/55.0"; #[cfg(all(target_os = "linux", not(target_arch = "x86_64")))] const DESKTOP_UA_STRING: &'static str = - "Mozilla/5.0 (X11; Linux i686; rv:63.0) Servo/1.0 Firefox/63.0"; + "Mozilla/5.0 (X11; Linux i686; rv:55.0) Servo/1.0 Firefox/55.0"; #[cfg(all(target_os = "windows", target_arch = "x86_64"))] const DESKTOP_UA_STRING: &'static str = - "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:63.0) Servo/1.0 Firefox/63.0"; + "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:55.0) Servo/1.0 Firefox/55.0"; #[cfg(all(target_os = "windows", not(target_arch = "x86_64")))] const DESKTOP_UA_STRING: &'static str = - "Mozilla/5.0 (Windows NT 6.1; rv:63.0) Servo/1.0 Firefox/63.0"; + "Mozilla/5.0 (Windows NT 6.1; rv:55.0) Servo/1.0 Firefox/55.0"; #[cfg(not(any(target_os = "linux", target_os = "windows")))] // Neither Linux nor Windows, so maybe OS X, and if not then OS X is an okay fallback. const DESKTOP_UA_STRING: &'static str = - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:63.0) Servo/1.0 Firefox/63.0"; + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:55.0) Servo/1.0 Firefox/55.0"; match agent { UserAgent::Desktop => DESKTOP_UA_STRING, - UserAgent::Android => "Mozilla/5.0 (Android; Mobile; rv:63.0) Servo/1.0 Firefox/63.0", + UserAgent::Android => "Mozilla/5.0 (Android; Mobile; rv:55.0) Servo/1.0 Firefox/55.0", UserAgent::iOS => { - "Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X; rv:63.0) Servo/1.0 Firefox/63.0" + "Mozilla/5.0 (iPhone; CPU iPhone OS 8_3 like Mac OS X; rv:55.0) Servo/1.0 Firefox/55.0" }, } } @@ -602,7 +600,6 @@ pub fn default_opts() -> Opts { certificate_path: None, unminify_js: false, print_pwm: false, - clean_shutdown: false, } } @@ -755,11 +752,6 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { "config directory following xdg spec on linux platform", "", ); - opts.optflag( - "", - "clean-shutdown", - "Do not shutdown until all threads have finished (macos only)", - ); opts.optflag("v", "version", "Display servo version information"); opts.optflag("", "unminify-js", "Unminify Javascript"); opts.optopt("", "profiler-db-user", "Profiler database user", ""); @@ -813,8 +805,7 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { .or_else(|error| { warn!("URL parsing failed ({:?}).", error); Err(error) - }) - .ok() + }).ok() }); let tile_size: usize = match opt_match.opt_str("s") { @@ -940,8 +931,7 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { r.parse().unwrap_or_else(|err| { args_fail(&format!("Error parsing option: --resolution ({})", err)) }) - }) - .collect(); + }).collect(); TypedSize2D::new(res[0], res[1]) }, None => TypedSize2D::new(1024, 740), @@ -971,19 +961,13 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { .read_to_end(&mut contents) .unwrap_or_else(|err| args_fail(&format!("Couldn't read {}: {}", filename, err))); (contents, url) - }) - .collect(); + }).collect(); let do_not_use_native_titlebar = opt_match.opt_present("b") || !PREFS .get("shell.native-titlebar.enabled") .as_boolean() .unwrap(); - let enable_subpixel_text_antialiasing = !debug_options.disable_subpixel_aa && PREFS - .get("gfx.subpixel-text-antialiasing.enabled") - .as_boolean() - .unwrap(); - let is_printing_version = opt_match.opt_present("v") || opt_match.opt_present("version"); let opts = Opts { @@ -1019,7 +1003,7 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { show_debug_fragment_borders: debug_options.show_fragment_borders, show_debug_parallel_layout: debug_options.show_parallel_layout, enable_text_antialiasing: !debug_options.disable_text_aa, - enable_subpixel_text_antialiasing: enable_subpixel_text_antialiasing, + enable_subpixel_text_antialiasing: !debug_options.disable_subpixel_aa, enable_canvas_antialiasing: !debug_options.disable_canvas_aa, dump_style_tree: debug_options.dump_style_tree, dump_rule_tree: debug_options.dump_rule_tree, @@ -1046,7 +1030,6 @@ pub fn from_cmdline_args(args: &[String]) -> ArgumentParsingResult { certificate_path: opt_match.opt_str("certificate-path"), unminify_js: opt_match.opt_present("unminify-js"), print_pwm: opt_match.opt_present("print-pwm"), - clean_shutdown: opt_match.opt_present("clean-shutdown"), }; set_defaults(opts); diff --git a/components/config/prefs.rs b/components/config/prefs.rs index 91bbc35fca51..792f3c9fb8f7 100644 --- a/components/config/prefs.rs +++ b/components/config/prefs.rs @@ -2,15 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::basedir::default_config_dir; -use crate::opts; +use basedir::default_config_dir; use embedder_traits::resources::{self, Resource}; -use serde_json::{self, Value}; +use num_cpus; +use opts; +use rustc_serialize::json::{Json, ToJson}; use std::borrow::ToOwned; use std::cmp::max; use std::collections::HashMap; use std::fs::File; -use std::io::{stderr, Read, Write}; +use std::io::{Read, Write, stderr}; use std::path::PathBuf; use std::sync::{Arc, RwLock}; @@ -33,17 +34,13 @@ pub enum PrefValue { } impl PrefValue { - pub fn from_json(data: Value) -> Result { + pub fn from_json(data: Json) -> Result { let value = match data { - Value::Bool(x) => PrefValue::Boolean(x), - Value::String(x) => PrefValue::String(x), - Value::Number(x) => { - if let Some(v) = x.as_f64() { - PrefValue::Number(v) - } else { - return Err(()); - } - }, + Json::Boolean(x) => PrefValue::Boolean(x), + Json::String(x) => PrefValue::String(x), + Json::F64(x) => PrefValue::Number(x), + Json::I64(x) => PrefValue::Number(x as f64), + Json::U64(x) => PrefValue::Number(x as f64), _ => return Err(()), }; Ok(value) @@ -78,6 +75,17 @@ impl PrefValue { } } +impl ToJson for PrefValue { + fn to_json(&self) -> Json { + match *self { + PrefValue::Boolean(x) => Json::Boolean(x), + PrefValue::String(ref x) => Json::String(x.clone()), + PrefValue::Number(x) => Json::F64(x), + PrefValue::Missing => Json::Null, + } + } +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub enum Pref { NoDefault(Arc), @@ -93,7 +101,7 @@ impl Pref { Pref::WithDefault(Arc::new(value), None) } - fn from_json(data: Value) -> Result { + fn from_json(data: Json) -> Result { let value = PrefValue::from_json(data)?; Ok(Pref::new_default(value)) } @@ -118,6 +126,12 @@ impl Pref { } } +impl ToJson for Pref { + fn to_json(&self) -> Json { + self.value().to_json() + } +} + pub fn default_prefs() -> Preferences { let prefs = Preferences(Arc::new(RwLock::new(HashMap::new()))); prefs.set( @@ -128,13 +142,13 @@ pub fn default_prefs() -> Preferences { } pub fn read_prefs(txt: &str) -> Result, ()> { - let json: Value = serde_json::from_str(txt).or_else(|e| { + let json = Json::from_str(txt).or_else(|e| { println!("Ignoring invalid JSON in preferences: {:?}.", e); Err(()) })?; let mut prefs = HashMap::new(); - if let Value::Object(obj) = json { + if let Json::Object(obj) = json { for (name, value) in obj.into_iter() { match Pref::from_json(value) { Ok(x) => { @@ -178,8 +192,7 @@ fn init_user_prefs(path: &mut PathBuf) { writeln!( &mut stderr(), "Error opening prefs.json from config directory" - ) - .expect("failed printing to stderr"); + ).expect("failed printing to stderr"); } } diff --git a/components/config/tests/opts.rs b/components/config/tests/opts.rs index 030f398a7cb2..e2db853a991c 100644 --- a/components/config/tests/opts.rs +++ b/components/config/tests/opts.rs @@ -2,7 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use servo_config::opts::{parse_pref_from_command_line, parse_url_or_filename}; +extern crate servo_config; + +use servo_config::opts::{parse_url_or_filename, parse_pref_from_command_line}; use servo_config::prefs::{PrefValue, PREFS}; use std::path::Path; diff --git a/components/config/tests/prefs.rs b/components/config/tests/prefs.rs index e4ff276ebb57..823b03b76c2e 100644 --- a/components/config/tests/prefs.rs +++ b/components/config/tests/prefs.rs @@ -2,8 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate servo_config; + use servo_config::basedir; -use servo_config::prefs::{read_prefs, PrefValue, PREFS}; +use servo_config::prefs::{PREFS, PrefValue, read_prefs}; use std::fs::{self, File}; use std::io::{Read, Write}; diff --git a/components/constellation/Cargo.toml b/components/constellation/Cargo.toml index 1e57a10e6f28..599f9f7e6e05 100644 --- a/components/constellation/Cargo.toml +++ b/components/constellation/Cargo.toml @@ -3,7 +3,6 @@ name = "constellation" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -23,10 +22,9 @@ euclid = "0.19" embedder_traits = { path = "../embedder_traits" } gfx = {path = "../gfx"} gfx_traits = {path = "../gfx_traits"} -http = "0.1" +hyper = "0.10" ipc-channel = "0.11" layout_traits = {path = "../layout_traits"} -keyboard-types = {version = "0.4.2-servo", features = ["serde"]} log = "0.4" metrics = {path = "../metrics"} msg = {path = "../msg"} @@ -46,3 +44,6 @@ webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} [target.'cfg(all(not(target_os = "windows"), not(target_os = "ios")))'.dependencies] gaol = {git = "https://github.com/servo/gaol"} + +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"] } diff --git a/components/constellation/browsingcontext.rs b/components/constellation/browsingcontext.rs index 06db6f7d58c7..c4415ff169ce 100644 --- a/components/constellation/browsingcontext.rs +++ b/components/constellation/browsingcontext.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::pipeline::Pipeline; use euclid::TypedSize2D; use msg::constellation_msg::{BrowsingContextId, PipelineId, TopLevelBrowsingContextId}; +use pipeline::Pipeline; use std::collections::{HashMap, HashSet}; use style_traits::CSSPixel; diff --git a/components/constellation/constellation.rs b/components/constellation/constellation.rs index 2c693273b0fa..9973e4fb9236 100644 --- a/components/constellation/constellation.rs +++ b/components/constellation/constellation.rs @@ -91,67 +91,55 @@ use backtrace::Backtrace; use bluetooth_traits::BluetoothRequest; +use browsingcontext::{AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator}; +use browsingcontext::NewBrowsingContextInfo; use canvas::canvas_paint_thread::CanvasPaintThread; use canvas::webgl_thread::WebGLThreads; use canvas_traits::canvas::CanvasId; use canvas_traits::canvas::CanvasMsg; use clipboard::{ClipboardContext, ClipboardProvider}; +use compositing::SendableFrameTree; use compositing::compositor_thread::CompositorProxy; use compositing::compositor_thread::Msg as ToCompositorMsg; -use compositing::SendableFrameTree; -use crate::browsingcontext::NewBrowsingContextInfo; -use crate::browsingcontext::{ - AllBrowsingContextsIterator, BrowsingContext, FullyActiveBrowsingContextsIterator, -}; -use crate::event_loop::EventLoop; -use crate::network_listener::NetworkListener; -use crate::pipeline::{InitialPipelineState, Pipeline}; -use crate::session_history::{ - JointSessionHistory, NeedsToReload, SessionHistoryChange, SessionHistoryDiff, -}; -use crate::timer_scheduler::TimerScheduler; +use debugger; use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg}; use embedder_traits::{EmbedderMsg, EmbedderProxy}; -use euclid::{Size2D, TypedScale, TypedSize2D}; +use euclid::{Size2D, TypedSize2D, TypedScale}; +use event_loop::EventLoop; use gfx::font_cache_thread::FontCacheThread; use gfx_traits::Epoch; -use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; +use ipc_channel::{Error as IpcError}; +use ipc_channel::ipc::{self, IpcSender, IpcReceiver}; use ipc_channel::router::ROUTER; -use ipc_channel::Error as IpcError; -use keyboard_types::KeyboardEvent; use layout_traits::LayoutThreadFactory; -use log::{Level, LevelFilter, Log, Metadata, Record}; -use msg::constellation_msg::{ - BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, -}; +use log::{Log, Level, LevelFilter, Metadata, Record}; +use msg::constellation_msg::{BrowsingContextId, PipelineId, HistoryStateId, TopLevelBrowsingContextId}; +use msg::constellation_msg::{Key, KeyModifiers, KeyState}; use msg::constellation_msg::{PipelineNamespace, PipelineNamespaceId, TraversalDirection}; +use net_traits::{self, IpcSend, FetchResponseMsg, ResourceThreads}; use net_traits::pub_domains::reg_host; use net_traits::request::RequestInit; use net_traits::storage_thread::{StorageThreadMsg, StorageType}; -use net_traits::{self, FetchResponseMsg, IpcSend, ResourceThreads}; +use network_listener::NetworkListener; +use pipeline::{InitialPipelineState, Pipeline}; use profile_traits::mem; use profile_traits::time; -use script_traits::{webdriver_msg, LogEntry, ScriptToConstellationChan, ServiceWorkerMsg}; -use script_traits::{ - AnimationState, AnimationTickType, AuxiliaryBrowsingContextLoadInfo, CompositorEvent, -}; -use script_traits::{ - ConstellationControlMsg, ConstellationMsg as FromCompositorMsg, DiscardBrowsingContext, -}; +use script_traits::{AnimationState, AuxiliaryBrowsingContextLoadInfo, AnimationTickType, CompositorEvent}; +use script_traits::{ConstellationControlMsg, ConstellationMsg as FromCompositorMsg, DiscardBrowsingContext}; use script_traits::{DocumentActivity, DocumentState, LayoutControlMsg, LoadData}; -use script_traits::{ - IFrameLoadInfo, IFrameLoadInfoWithData, IFrameSandboxState, TimerSchedulerMsg, -}; +use script_traits::{IFrameLoadInfo, IFrameLoadInfoWithData, IFrameSandboxState, TimerSchedulerMsg}; use script_traits::{LayoutMsg as FromLayoutMsg, ScriptMsg as FromScriptMsg, ScriptThreadFactory}; +use script_traits::{LogEntry, ScriptToConstellationChan, ServiceWorkerMsg, webdriver_msg}; use script_traits::{SWManagerMsg, ScopeThings, UpdatePipelineIdReason, WebDriverCommandMsg}; use script_traits::{WindowSizeData, WindowSizeType}; use serde::{Deserialize, Serialize}; -use servo_channel::{channel, Receiver, Sender}; +use servo_channel::{Receiver, Sender, channel}; use servo_config::opts; use servo_config::prefs::PREFS; -use servo_rand::{random, Rng, SeedableRng, ServoRng}; +use servo_rand::{Rng, SeedableRng, ServoRng, random}; use servo_remutex::ReentrantMutex; use servo_url::{Host, ImmutableOrigin, ServoUrl}; +use session_history::{JointSessionHistory, NeedsToReload, SessionHistoryChange, SessionHistoryDiff}; use std::borrow::ToOwned; use std::collections::{HashMap, VecDeque}; use std::marker::PhantomData; @@ -160,23 +148,13 @@ use std::process; use std::rc::{Rc, Weak}; use std::sync::Arc; use std::thread; +use style_traits::CSSPixel; use style_traits::cursor::CursorKind; use style_traits::viewport::ViewportConstraints; -use style_traits::CSSPixel; +use timer_scheduler::TimerScheduler; +use webrender_api; use webvr_traits::{WebVREvent, WebVRMsg}; -/// Servo supports tabs (referred to as browsers), so `Constellation` needs to -/// store browser specific data for bookkeeping. -struct Browser { - /// The currently focused browsing context in this browser for key events. - /// The focused pipeline is the current entry of the focused browsing - /// context. - focused_browsing_context_id: BrowsingContextId, - - /// The joint session history for this browser. - session_history: JointSessionHistory, -} - /// The `Constellation` itself. In the servo browser, there is one /// constellation, which maintains all of the browser global data. /// In embedded applications, there may be more than one constellation, @@ -223,17 +201,13 @@ pub struct Constellation { /// constellation to send messages to the compositor thread. compositor_proxy: CompositorProxy, - /// The last frame tree sent to WebRender, denoting the browser (tab) user - /// has currently selected. This also serves as the key to retrieve data - /// about the current active browser from `browsers`. + /// The last frame tree sent to WebRender. active_browser_id: Option, - /// Bookkeeping data for all browsers in constellation. - browsers: HashMap, - /// Channels for the constellation to send messages to the public - /// resource-related threads. There are two groups of resource threads: one - /// for public browsing, and one for private browsing. + /// resource-related threads. There are two groups of resource + /// threads: one for public browsing, and one for private + /// browsing. public_resource_threads: ResourceThreads, /// Channels for the constellation to send messages to the private @@ -299,8 +273,10 @@ pub struct Constellation { /// to become same-origin, at which point they can share DOM objects. event_loops: HashMap>, - /// The set of all the pipelines in the browser. (See the `pipeline` module - /// for more details.) + joint_session_histories: HashMap, + + /// The set of all the pipelines in the browser. + /// (See the `pipeline` module for more details.) pipelines: HashMap, /// The set of all the browsing contexts in the browser. @@ -313,6 +289,9 @@ pub struct Constellation { /// we store a `SessionHistoryChange` object for the navigation in progress. pending_changes: Vec, + /// The currently focused pipeline for key events. + focus_pipeline_id: Option, + /// Pipeline IDs are namespaced in order to avoid name collisions, /// and the namespaces are allocated by the constellation. next_pipeline_namespace_id: PipelineNamespaceId, @@ -610,7 +589,6 @@ where embedder_proxy: state.embedder_proxy, compositor_proxy: state.compositor_proxy, active_browser_id: None, - browsers: HashMap::new(), debugger_chan: state.debugger_chan, devtools_chan: state.devtools_chan, bluetooth_thread: state.bluetooth_thread, @@ -621,12 +599,14 @@ where swmanager_receiver: swmanager_receiver, swmanager_sender: sw_mgr_clone, event_loops: HashMap::new(), + joint_session_histories: HashMap::new(), pipelines: HashMap::new(), browsing_contexts: HashMap::new(), pending_changes: vec![], // We initialize the namespace at 2, since we reserved // namespace 0 for the embedder, and 0 for the constellation next_pipeline_namespace_id: PipelineNamespaceId(2), + focus_pipeline_id: None, time_profiler_chan: state.time_profiler_chan, mem_profiler_chan: state.mem_profiler_chan, window_size: WindowSizeData { @@ -728,8 +708,9 @@ where match reg_host(&load_data.url) { None => (None, None), Some(host) => { - let event_loop = - self.event_loops.get(&host).and_then(|weak| weak.upgrade()); + let event_loop = self + .event_loops.get(&host) + .and_then(|weak| weak.upgrade()); match event_loop { None => (None, Some(host)), Some(event_loop) => (Some(event_loop.clone()), None), @@ -864,8 +845,7 @@ where is_private, is_visible, ); - self.browsing_contexts - .insert(browsing_context_id, browsing_context); + self.browsing_contexts.insert(browsing_context_id, browsing_context); // If this context is a nested container, attach it to parent pipeline. if let Some(parent_pipeline_id) = parent_pipeline_id { @@ -876,16 +856,12 @@ where } fn add_pending_change(&mut self, change: SessionHistoryChange) { - self.handle_load_start_msg( - change.top_level_browsing_context_id, - change.browsing_context_id, - ); + self.handle_load_start_msg(change.top_level_browsing_context_id, change.browsing_context_id); self.pending_changes.push(change); } /// Handles loading pages, navigation, and granting access to the compositor fn handle_request(&mut self) { - #[derive(Debug)] enum Request { Script((PipelineId, FromScriptMsg)), Compositor(FromCompositorMsg), @@ -985,12 +961,19 @@ where self.handle_get_pipeline(browsing_context_id, resp_chan); }, FromCompositorMsg::GetFocusTopLevelBrowsingContext(resp_chan) => { - // The focused browsing context's top-level browsing context is - // the active browser's id itself. - let _ = resp_chan.send(self.active_browser_id); + let focus_browsing_context = self + .focus_pipeline_id + .and_then(|pipeline_id| self.pipelines.get(&pipeline_id)) + .map(|pipeline| pipeline.top_level_browsing_context_id) + .filter(|&top_level_browsing_context_id| { + let browsing_context_id = + BrowsingContextId::from(top_level_browsing_context_id); + self.browsing_contexts.contains_key(&browsing_context_id) + }); + let _ = resp_chan.send(focus_browsing_context); }, - FromCompositorMsg::Keyboard(key_event) => { - self.handle_key_msg(key_event); + FromCompositorMsg::KeyEvent(ch, key, state, modifiers) => { + self.handle_key_msg(ch, key, state, modifiers); }, // Load a new page from a typed url // If there is already a pending page (self.pending_changes), it will not be overridden; @@ -1212,7 +1195,7 @@ where } }, FromScriptMsg::CreateCanvasPaintThread(size, sender) => { - self.handle_create_canvas_paint_thread_msg(size, sender) + self.handle_create_canvas_paint_thread_msg(&size, sender) }, FromScriptMsg::SetDocumentState(state) => { self.document_states.insert(source_pipeline_id, state); @@ -1242,22 +1225,14 @@ where .and_then(|pipeline| self.browsing_contexts.get(&pipeline.browsing_context_id)) .map(|ctx| (ctx.id, ctx.parent_pipeline_id)); if let Err(e) = sender.send(result) { - warn!( - "Sending reply to get browsing context info failed ({:?}).", - e - ); + warn!("Sending reply to get browsing context info failed ({:?}).", e); } }, FromScriptMsg::GetTopForBrowsingContext(browsing_context_id, sender) => { - let result = self - .browsing_contexts - .get(&browsing_context_id) + let result = self.browsing_contexts.get(&browsing_context_id) .and_then(|bc| Some(bc.top_level_id)); if let Err(e) = sender.send(result) { - warn!( - "Sending reply to get top for browsing context info failed ({:?}).", - e - ); + warn!("Sending reply to get top for browsing context info failed ({:?}).", e); } }, FromScriptMsg::GetChildBrowsingContextId(browsing_context_id, index, sender) => { @@ -1466,11 +1441,6 @@ where } } - debug!("Exiting Canvas Paint thread."); - if let Err(e) = self.canvas_chan.send(CanvasMsg::Exit) { - warn!("Exit Canvas Paint thread failed ({})", e); - } - if let Some(webgl_threads) = self.webgl_threads.as_ref() { debug!("Exiting WebGL thread."); if let Err(e) = webgl_threads.exit() { @@ -1662,14 +1632,11 @@ where fn handle_new_top_level_browsing_context( &mut self, url: ServoUrl, - top_level_browsing_context_id: TopLevelBrowsingContextId, + top_level_browsing_context_id: TopLevelBrowsingContextId ) { let window_size = self.window_size.initial_viewport; let pipeline_id = PipelineId::new(); - let msg = ( - Some(top_level_browsing_context_id), - EmbedderMsg::BrowserCreated(top_level_browsing_context_id), - ); + let msg = (Some(top_level_browsing_context_id), EmbedderMsg::BrowserCreated(top_level_browsing_context_id)); self.embedder_proxy.send(msg); let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id); let load_data = LoadData::new(url.clone(), None, None, None); @@ -1677,16 +1644,11 @@ where let is_private = false; let is_visible = true; - // Register this new top-level browsing context id as a browser and set - // its focused browsing context to be itself. - self.browsers.insert( - top_level_browsing_context_id, - Browser { - focused_browsing_context_id: browsing_context_id, - session_history: JointSessionHistory::new(), - }, - ); - + if self.focus_pipeline_id.is_none() { + self.focus_pipeline_id = Some(pipeline_id); + } + self.joint_session_histories + .insert(top_level_browsing_context_id, JointSessionHistory::new()); self.new_pipeline( pipeline_id, browsing_context_id, @@ -1718,10 +1680,6 @@ where ) { let browsing_context_id = BrowsingContextId::from(top_level_browsing_context_id); self.close_browsing_context(browsing_context_id, ExitPipelineMode::Normal); - self.browsers.remove(&top_level_browsing_context_id); - if self.active_browser_id == Some(top_level_browsing_context_id) { - self.active_browser_id = None; - } } fn handle_iframe_size_msg( @@ -1745,12 +1703,11 @@ where }; let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) { Some(browsing_context) => browsing_context.parent_pipeline_id, - None => { - return warn!( - "Subframe {} loaded in closed browsing context {}.", - pipeline_id, browsing_context_id, - ) - }, + None => return warn!( + "Subframe {} loaded in closed browsing context {}.", + pipeline_id, + browsing_context_id, + ), }; let parent_pipeline_id = match parent_pipeline_id { Some(parent_pipeline_id) => parent_pipeline_id, @@ -1807,8 +1764,7 @@ where let (load_data, is_private) = { // If no url is specified, reload. - let old_pipeline = load_info - .old_pipeline_id + let old_pipeline = load_info.old_pipeline_id .and_then(|id| self.pipelines.get(&id)); let load_data = load_info.load_data.unwrap_or_else(|| { let url = match old_pipeline { @@ -1821,25 +1777,23 @@ where }); let is_parent_private = { - let parent_browsing_context_id = match self.pipelines.get(&parent_pipeline_id) { - Some(pipeline) => pipeline.browsing_context_id, - None => { - return warn!( + let parent_browsing_context_id = + match self.pipelines.get(&parent_pipeline_id) { + Some(pipeline) => pipeline.browsing_context_id, + None => return warn!( "Script loaded url in iframe {} in closed parent pipeline {}.", - browsing_context_id, parent_pipeline_id, - ) - }, - }; + browsing_context_id, + parent_pipeline_id, + ), + }; let is_parent_private = match self.browsing_contexts.get(&parent_browsing_context_id) { Some(ctx) => ctx.is_private, - None => { - return warn!( + None => return warn!( "Script loaded url in iframe {} in closed parent browsing context {}.", browsing_context_id, parent_browsing_context_id, - ) - }, + ), }; is_parent_private }; @@ -1851,12 +1805,10 @@ where let (replace, window_size, is_visible) = { let browsing_context = match self.browsing_contexts.get(&browsing_context_id) { Some(ctx) => ctx, - None => { - return warn!( - "Script loaded url in iframe with closed browsing context {}.", - browsing_context_id, - ) - }, + None => return warn!( + "Script loaded url in iframe with closed browsing context {}.", + browsing_context_id, + ), }; let replace = if replace { Some(NeedsToReload::No(browsing_context.pipeline_id)) @@ -1909,22 +1861,19 @@ where let load_data = LoadData::new(url.clone(), Some(parent_pipeline_id), None, None); let (pipeline, is_private, is_visible) = { - let (script_sender, parent_browsing_context_id) = match self - .pipelines - .get(&parent_pipeline_id) - { - Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id), - None => return warn!("Script loaded url in closed iframe {}.", parent_pipeline_id), - }; + let (script_sender, parent_browsing_context_id) = + match self.pipelines.get(&parent_pipeline_id) { + Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id), + None => return warn!("Script loaded url in closed iframe {}.", parent_pipeline_id), + }; let (is_parent_private, is_parent_visible) = match self.browsing_contexts.get(&parent_browsing_context_id) { Some(ctx) => (ctx.is_private, ctx.is_visible), - None => { - return warn!( - "New iframe {} loaded in closed parent browsing context {}.", - browsing_context_id, parent_browsing_context_id, - ) - }, + None => return warn!( + "New iframe {} loaded in closed parent browsing context {}.", + browsing_context_id, + parent_browsing_context_id, + ), }; let is_private = is_private || is_parent_private; let pipeline = Pipeline::new( @@ -1959,11 +1908,9 @@ where }); } - fn handle_script_new_auxiliary( - &mut self, - load_info: AuxiliaryBrowsingContextLoadInfo, - layout_sender: IpcSender, - ) { + fn handle_script_new_auxiliary(&mut self, + load_info: AuxiliaryBrowsingContextLoadInfo, + layout_sender: IpcSender) { let AuxiliaryBrowsingContextLoadInfo { opener_pipeline_id, new_top_level_browsing_context_id, @@ -1980,22 +1927,19 @@ where let (script_sender, opener_browsing_context_id) = match self.pipelines.get(&opener_pipeline_id) { Some(pipeline) => (pipeline.event_loop.clone(), pipeline.browsing_context_id), - None => { - return warn!( - "Auxiliary loaded url in closed iframe {}.", - opener_pipeline_id - ) - }, + None => return warn!( + "Auxiliary loaded url in closed iframe {}.", + opener_pipeline_id + ), }; let (is_opener_private, is_opener_visible) = match self.browsing_contexts.get(&opener_browsing_context_id) { Some(ctx) => (ctx.is_private, ctx.is_visible), - None => { - return warn!( - "New auxiliary {} loaded in closed opener browsing context {}.", - new_browsing_context_id, opener_browsing_context_id, - ) - }, + None => return warn!( + "New auxiliary {} loaded in closed opener browsing context {}.", + new_browsing_context_id, + opener_browsing_context_id, + ), }; let pipeline = Pipeline::new( new_pipeline_id, @@ -2007,7 +1951,7 @@ where self.compositor_proxy.clone(), url, is_opener_visible, - load_data, + load_data ); (pipeline, is_opener_private, is_opener_visible) @@ -2015,13 +1959,7 @@ where assert!(!self.pipelines.contains_key(&new_pipeline_id)); self.pipelines.insert(new_pipeline_id, pipeline); - self.browsers.insert( - new_top_level_browsing_context_id, - Browser { - focused_browsing_context_id: new_browsing_context_id, - session_history: JointSessionHistory::new(), - }, - ); + self.joint_session_histories.insert(new_top_level_browsing_context_id, JointSessionHistory::new()); self.add_pending_change(SessionHistoryChange { top_level_browsing_context_id: new_top_level_browsing_context_id, browsing_context_id: new_browsing_context_id, @@ -2142,7 +2080,8 @@ where // against future changes that might break things. warn!( "Pipeline {} loaded url in closed browsing context {}.", - source_id, browsing_context_id, + source_id, + browsing_context_id, ); return None; }, @@ -2491,13 +2430,12 @@ where // TODO: Save the sandbox state so it can be restored here. let sandbox = IFrameSandboxState::IFrameUnsandboxed; - let ( - top_level_id, - old_pipeline_id, - parent_pipeline_id, - window_size, - is_private, - is_visible, + let (top_level_id, + old_pipeline_id, + parent_pipeline_id, + window_size, + is_private, + is_visible ) = match self.browsing_contexts.get(&browsing_context_id) { Some(ctx) => ( ctx.top_level_id, @@ -2613,9 +2551,9 @@ where sender: IpcSender, ) { let length = self - .browsers + .joint_session_histories .get(&top_level_browsing_context_id) - .map(|browser| browser.session_history.history_length()) + .map(JointSessionHistory::history_length) .unwrap_or(1); let _ = sender.send(length as u32); } @@ -2683,25 +2621,12 @@ where session_history.replace_history_state(pipeline_id, history_state_id, url); } - fn handle_key_msg(&mut self, event: KeyboardEvent) { - // Send to the focused browsing contexts' current pipeline. If it - // doesn't exist, fall back to sending to the compositor. - let focused_browsing_context_id = self - .active_browser_id - .and_then(|browser_id| self.browsers.get(&browser_id)) - .map(|browser| browser.focused_browsing_context_id); - match focused_browsing_context_id { - Some(browsing_context_id) => { - let event = CompositorEvent::KeyboardEvent(event); - let pipeline_id = match self.browsing_contexts.get(&browsing_context_id) { - Some(ctx) => ctx.pipeline_id, - None => { - return warn!( - "Got key event for nonexistent browsing context {}.", - browsing_context_id, - ) - }, - }; + fn handle_key_msg(&mut self, ch: Option, key: Key, state: KeyState, mods: KeyModifiers) { + // Send to the explicitly focused pipeline. If it doesn't exist, fall back to sending to + // the compositor. + match self.focus_pipeline_id { + Some(pipeline_id) => { + let event = CompositorEvent::KeyEvent(ch, key, state, mods); let msg = ConstellationControlMsg::SendEvent(pipeline_id, event); let result = match self.pipelines.get(&pipeline_id) { Some(pipeline) => pipeline.event_loop.send(msg), @@ -2714,7 +2639,7 @@ where } }, None => { - let event = (None, EmbedderMsg::Keyboard(event)); + let event = (None, EmbedderMsg::KeyEvent(ch, key, state, mods)); self.embedder_proxy.clone().send(event); }, } @@ -2802,66 +2727,37 @@ where } fn handle_focus_msg(&mut self, pipeline_id: PipelineId) { - let (browsing_context_id, top_level_browsing_context_id) = - match self.pipelines.get(&pipeline_id) { - Some(pipeline) => ( - pipeline.browsing_context_id, - pipeline.top_level_browsing_context_id, - ), - None => return warn!("Pipeline {:?} focus parent after closure.", pipeline_id), - }; - - // Update the focused browsing context in its browser in `browsers`. - match self.browsers.get_mut(&top_level_browsing_context_id) { - Some(browser) => { - browser.focused_browsing_context_id = browsing_context_id; - }, - None => { - return warn!( - "Browser {} for focus msg does not exist", - top_level_browsing_context_id - ) - }, - }; + self.focus_pipeline_id = Some(pipeline_id); // Focus parent iframes recursively - self.focus_parent_pipeline(browsing_context_id); + self.focus_parent_pipeline(pipeline_id); } - fn focus_parent_pipeline(&mut self, browsing_context_id: BrowsingContextId) { + fn focus_parent_pipeline(&mut self, pipeline_id: PipelineId) { + let browsing_context_id = match self.pipelines.get(&pipeline_id) { + Some(pipeline) => pipeline.browsing_context_id, + None => return warn!("Pipeline {:?} focus parent after closure.", pipeline_id), + }; let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) { Some(ctx) => ctx.parent_pipeline_id, - None => { - return warn!( - "Browsing context {:?} focus parent after closure.", - browsing_context_id - ) - }, + None => return warn!("Browsing context {:?} focus parent after closure.", browsing_context_id), }; let parent_pipeline_id = match parent_pipeline_id { - Some(parent_id) => parent_id, - None => { - return debug!( - "Browsing context {:?} focus has no parent.", - browsing_context_id - ) - }, + Some(info) => info, + None => return debug!("Pipeline {:?} focus has no parent.", pipeline_id), }; - // Send a message to the parent of the provided browsing context (if it - // exists) telling it to mark the iframe element as focused. + // Send a message to the parent of the provided pipeline (if it exists) + // telling it to mark the iframe element as focused. let msg = ConstellationControlMsg::FocusIFrame(parent_pipeline_id, browsing_context_id); - let (result, parent_browsing_context_id) = match self.pipelines.get(&parent_pipeline_id) { - Some(pipeline) => { - let result = pipeline.event_loop.send(msg); - (result, pipeline.browsing_context_id) - }, + let result = match self.pipelines.get(&parent_pipeline_id) { + Some(pipeline) => pipeline.event_loop.send(msg), None => return warn!("Pipeline {:?} focus after closure.", parent_pipeline_id), }; if let Err(e) = result { self.handle_send_error(parent_pipeline_id, e); } - self.focus_parent_pipeline(parent_browsing_context_id); + self.focus_parent_pipeline(parent_pipeline_id); } fn handle_remove_iframe_msg( @@ -2915,12 +2811,7 @@ where }; let parent_pipeline_id = match self.browsing_contexts.get(&browsing_context_id) { Some(ctx) => ctx.parent_pipeline_id, - None => { - return warn!( - "Visibility change for closed browsing context {:?}.", - pipeline_id - ) - }, + None => return warn!("Visibility change for closed browsing context {:?}.", pipeline_id), }; if let Some(parent_pipeline_id) = parent_pipeline_id { @@ -2942,7 +2833,7 @@ where fn handle_create_canvas_paint_thread_msg( &mut self, - size: Size2D, + size: &Size2D, response_sender: IpcSender<(IpcSender, CanvasId)>, ) { let webrender_api = self.webrender_api_sender.clone(); @@ -2952,7 +2843,7 @@ where if let Err(e) = sender.send(CanvasMsg::Create( canvas_id_sender, - size, + *size, webrender_api, opts::get().enable_canvas_antialiasing, )) { @@ -3034,8 +2925,8 @@ where Some(pipeline) => pipeline.event_loop.clone(), None => return warn!("Pipeline {} SendKeys after closure.", pipeline_id), }; - for event in cmd { - let event = CompositorEvent::KeyboardEvent(event); + for (key, mods, state) in cmd { + let event = CompositorEvent::KeyEvent(None, key, state, mods); let control_msg = ConstellationControlMsg::SendEvent(pipeline_id, event); if let Err(e) = event_loop.send(control_msg) { return self.handle_send_error(pipeline_id, e); @@ -3056,8 +2947,11 @@ where // LoadData of inner frames are ignored and replaced with the LoadData // of the parent. - let session_history = match self.browsers.get(&top_level_browsing_context_id) { - Some(browser) => &browser.session_history, + let session_history = match self + .joint_session_histories + .get(&top_level_browsing_context_id) + { + Some(session_history) => session_history, None => { return warn!( "Session history does not exist for {}", @@ -3201,15 +3095,11 @@ where change.browsing_context_id, change.new_pipeline_id ); - // If the currently focused browsing context is a child of the browsing - // context in which the page is being loaded, then update the focused - // browsing context to be the one where the page is being loaded. - if self.focused_browsing_context_is_descendant_of(change.browsing_context_id) { - self.browsers - .entry(change.top_level_browsing_context_id) - .and_modify(|browser| { - browser.focused_browsing_context_id = change.browsing_context_id - }); + // If the currently focused pipeline is the one being changed (or a child + // of the pipeline being changed) then update the focus pipeline to be + // the replacement. + if self.focused_pipeline_is_descendant_of(change.browsing_context_id) { + self.focus_pipeline_id = Some(change.new_pipeline_id); } let (old_pipeline_id, top_level_id) = @@ -3256,17 +3146,24 @@ where let (pipelines_to_close, states_to_close) = if let Some(replace_reloader) = change.replace { - self.get_joint_session_history(change.top_level_browsing_context_id) - .replace_reloader( - replace_reloader.clone(), - NeedsToReload::No(change.new_pipeline_id), - ); + let session_history = self + .joint_session_histories + .entry(change.top_level_browsing_context_id) + .or_insert(JointSessionHistory::new()); + session_history.replace_reloader( + replace_reloader.clone(), + NeedsToReload::No(change.new_pipeline_id), + ); match replace_reloader { NeedsToReload::No(pipeline_id) => (Some(vec![pipeline_id]), None), NeedsToReload::Yes(..) => (None, None), } } else { + let session_history = self + .joint_session_histories + .entry(change.top_level_browsing_context_id) + .or_insert(JointSessionHistory::new()); let diff = SessionHistoryDiff::BrowsingContextDiff { browsing_context_id: change.browsing_context_id, new_reloader: NeedsToReload::No(change.new_pipeline_id), @@ -3276,9 +3173,7 @@ where let mut pipelines_to_close = vec![]; let mut states_to_close = HashMap::new(); - let diffs_to_close = self - .get_joint_session_history(change.top_level_browsing_context_id) - .push_diff(diff); + let diffs_to_close = session_history.push_diff(diff); for diff in diffs_to_close { match diff { @@ -3348,21 +3243,6 @@ where self.update_frame_tree_if_active(change.top_level_browsing_context_id); } - fn focused_browsing_context_is_descendant_of( - &self, - browsing_context_id: BrowsingContextId, - ) -> bool { - let focused_browsing_context_id = self - .active_browser_id - .and_then(|browser_id| self.browsers.get(&browser_id)) - .map(|browser| browser.focused_browsing_context_id); - focused_browsing_context_id.map_or(false, |focus_ctx_id| { - focus_ctx_id == browsing_context_id || self - .fully_active_descendant_browsing_contexts_iter(browsing_context_id) - .any(|nested_ctx| nested_ctx.id == focus_ctx_id) - }) - } - fn trim_history(&mut self, top_level_browsing_context_id: TopLevelBrowsingContextId) { let pipelines_to_evict = { let session_history = self.get_joint_session_history(top_level_browsing_context_id); @@ -3445,12 +3325,11 @@ where // This is an existing browsing context. None => match self.browsing_contexts.get(&change.browsing_context_id) { Some(ctx) => ctx.parent_pipeline_id, - None => { - return warn!( - "Activated document {} after browsing context {} closure.", - change.new_pipeline_id, change.browsing_context_id, - ) - }, + None => return warn!( + "Activated document {} after browsing context {} closure.", + change.new_pipeline_id, + change.browsing_context_id, + ), }, }; if let Some(parent_pipeline_id) = parent_pipeline_id { @@ -3514,13 +3393,17 @@ where &mut self, pipeline_states: HashMap, ) -> ReadyToSave { - // Note that this function can panic, due to ipc-channel creation - // failure. Avoiding this panic would require a mechanism for dealing + // Note that this function can panic, due to ipc-channel creation failure. + // avoiding this panic would require a mechanism for dealing // with low-resource scenarios. // // If there is no focus browsing context yet, the initial page has // not loaded, so there is nothing to save yet. - let top_level_browsing_context_id = match self.active_browser_id { + let top_level_browsing_context_id = self + .focus_pipeline_id + .and_then(|pipeline_id| self.pipelines.get(&pipeline_id)) + .map(|pipeline| pipeline.top_level_browsing_context_id); + let top_level_browsing_context_id = match top_level_browsing_context_id { Some(id) => id, None => return ReadyToSave::NoTopLevelBrowsingContext, }; @@ -3695,14 +3578,12 @@ where new_size, size_type, )); - let pipeline_ids = browsing_context - .pipelines + let pipeline_ids = browsing_context.pipelines .iter() .filter(|pipeline_id| **pipeline_id != pipeline.id); for id in pipeline_ids { if let Some(pipeline) = self.pipelines.get(&id) { - let _ = pipeline - .event_loop + let _ = pipeline.event_loop .send(ConstellationControlMsg::ResizeInactive( pipeline.id, new_size, @@ -3805,24 +3686,17 @@ where top_level_browsing_context_id: TopLevelBrowsingContextId, pipeline_id: PipelineId, ) { - match self.browsers.get_mut(&top_level_browsing_context_id) { - Some(browser) => { - let load_data = match self.pipelines.get(&pipeline_id) { - Some(pipeline) => pipeline.load_data.clone(), - None => return warn!("Discarding closed pipeline {}", pipeline_id), - }; - browser.session_history.replace_reloader( - NeedsToReload::No(pipeline_id), - NeedsToReload::Yes(pipeline_id, load_data), - ); - }, - None => { - return warn!( - "Discarding pipeline {} after browser {} closure", - pipeline_id, top_level_browsing_context_id, - ) - }, + let load_data = match self.pipelines.get(&pipeline_id) { + Some(pipeline) => pipeline.load_data.clone(), + None => return, }; + self.joint_session_histories + .entry(top_level_browsing_context_id) + .or_insert(JointSessionHistory::new()) + .replace_reloader( + NeedsToReload::No(pipeline_id), + NeedsToReload::Yes(pipeline_id, load_data), + ); self.close_pipeline( pipeline_id, DiscardBrowsingContext::No, @@ -3904,10 +3778,8 @@ where // Randomly close a pipeline -if --random-pipeline-closure-probability is set fn maybe_close_random_pipeline(&mut self) { match self.random_pipeline_closure { - Some((ref mut rng, probability)) => { - if probability <= rng.gen::() { - return; - } + Some((ref mut rng, probability)) => if probability <= rng.gen::() { + return; }, _ => return, }; @@ -3943,17 +3815,9 @@ where &mut self, top_level_id: TopLevelBrowsingContextId, ) -> &mut JointSessionHistory { - &mut self - .browsers + self.joint_session_histories .entry(top_level_id) - // This shouldn't be necessary since `get_joint_session_history` is - // invoked for existing browsers but we need this to satisfy the - // type system. - .or_insert_with(|| Browser { - focused_browsing_context_id: BrowsingContextId::from(top_level_id), - session_history: JointSessionHistory::new(), - }) - .session_history + .or_insert(JointSessionHistory::new()) } // Convert a browsing context to a sendable form to pass to the compositor @@ -4017,4 +3881,11 @@ where .send(ToCompositorMsg::SetFrameTree(frame_tree)); } } + + fn focused_pipeline_is_descendant_of(&self, browsing_context_id: BrowsingContextId) -> bool { + self.focus_pipeline_id.map_or(false, |pipeline_id| { + self.fully_active_descendant_browsing_contexts_iter(browsing_context_id) + .any(|browsing_context| browsing_context.pipeline_id == pipeline_id) + }) + } } diff --git a/components/constellation/event_loop.rs b/components/constellation/event_loop.rs index ac8c06c29974..7506e029570a 100644 --- a/components/constellation/event_loop.rs +++ b/components/constellation/event_loop.rs @@ -6,8 +6,8 @@ //! view of a script thread. When an `EventLoop` is dropped, an `ExitScriptThread` //! message is sent to the script thread, asking it to shut down. -use ipc_channel::ipc::IpcSender; use ipc_channel::Error; +use ipc_channel::ipc::IpcSender; use script_traits::ConstellationControlMsg; use std::marker::PhantomData; use std::rc::Rc; diff --git a/components/constellation/lib.rs b/components/constellation/lib.rs index 1b4befa3af6e..1e0e9ed8ed4f 100644 --- a/components/constellation/lib.rs +++ b/components/constellation/lib.rs @@ -5,10 +5,42 @@ #![deny(unsafe_code)] #![cfg_attr(feature = "unstable", feature(conservative_impl_trait))] +extern crate backtrace; +extern crate bluetooth_traits; +extern crate canvas; +extern crate canvas_traits; +extern crate clipboard; +extern crate compositing; +extern crate debugger; +extern crate devtools_traits; +#[cfg(not(target_os = "ios"))] +extern crate embedder_traits; +extern crate euclid; +#[cfg(all(not(target_os = "windows"), not(target_os = "ios")))] +extern crate gaol; +extern crate gfx; +extern crate gfx_traits; +extern crate hyper; +extern crate ipc_channel; +extern crate layout_traits; #[macro_use] extern crate log; +extern crate metrics; +extern crate msg; +extern crate net; +extern crate net_traits; +extern crate profile_traits; +extern crate script_traits; +extern crate serde; #[macro_use] extern crate servo_channel; +extern crate servo_config; +extern crate servo_rand; +extern crate servo_remutex; +extern crate servo_url; +extern crate style_traits; +extern crate webrender_api; +extern crate webvr_traits; mod browsingcontext; mod constellation; @@ -20,9 +52,7 @@ mod sandboxing; mod session_history; mod timer_scheduler; -pub use crate::constellation::{ - Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState, -}; -pub use crate::pipeline::UnprivilegedPipelineContent; +pub use constellation::{Constellation, FromCompositorLogger, FromScriptLogger, InitialConstellationState}; +pub use pipeline::UnprivilegedPipelineContent; #[cfg(all(not(target_os = "windows"), not(target_os = "ios")))] -pub use crate::sandboxing::content_process_sandbox_profile; +pub use sandboxing::content_process_sandbox_profile; diff --git a/components/constellation/network_listener.rs b/components/constellation/network_listener.rs index a417f5cdeeb7..461be7990da4 100644 --- a/components/constellation/network_listener.rs +++ b/components/constellation/network_listener.rs @@ -6,15 +6,15 @@ //! Any redirects that are encountered are followed. Whenever a non-redirect //! response is received, it is forwarded to the appropriate script thread. -use http::header::LOCATION; +use hyper::header::Location; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use msg::constellation_msg::PipelineId; use net::http_loader::{set_default_accept, set_default_accept_language}; -use net_traits::request::{Destination, RequestInit}; -use net_traits::response::ResponseInit; use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata, FetchResponseMsg}; use net_traits::{IpcSend, NetworkError, ResourceThreads}; +use net_traits::request::{Destination, RequestInit}; +use net_traits::response::ResponseInit; use servo_channel::Sender; pub struct NetworkListener { @@ -99,7 +99,7 @@ impl NetworkListener { }; match metadata.headers { - Some(ref headers) if headers.contains_key(LOCATION) => { + Some(ref headers) if headers.has::() => { if self.req_init.url_list.is_empty() { self.req_init.url_list.push(self.req_init.url.clone()); } @@ -113,11 +113,6 @@ impl NetworkListener { location_url: metadata.location_url.clone(), headers: headers.clone().into_inner(), referrer: metadata.referrer.clone(), - status_code: metadata - .status - .as_ref() - .map(|&(code, _)| code) - .unwrap_or(200), }); // XXXManishearth we don't have the cancel_chan anymore and diff --git a/components/constellation/pipeline.rs b/components/constellation/pipeline.rs index 5d6cc038a140..d110bbfcdce3 100644 --- a/components/constellation/pipeline.rs +++ b/components/constellation/pipeline.rs @@ -4,23 +4,23 @@ use bluetooth_traits::BluetoothRequest; use canvas_traits::webgl::WebGLPipeline; -use compositing::compositor_thread::Msg as CompositorMsg; use compositing::CompositionPipeline; use compositing::CompositorProxy; -use crate::event_loop::EventLoop; +use compositing::compositor_thread::Msg as CompositorMsg; use devtools_traits::{DevtoolsControlMsg, ScriptToDevtoolsControlMsg}; -use euclid::{TypedScale, TypedSize2D}; +use euclid::{TypedSize2D, TypedScale}; +use event_loop::EventLoop; use gfx::font_cache_thread::FontCacheThread; +use ipc_channel::Error; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; -use ipc_channel::Error; use layout_traits::LayoutThreadFactory; use metrics::PaintTimeMetrics; -use msg::constellation_msg::TopLevelBrowsingContextId; use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, PipelineNamespaceId}; +use msg::constellation_msg::TopLevelBrowsingContextId; use net::image_cache::ImageCacheImpl; -use net_traits::image_cache::ImageCache; use net_traits::{IpcSend, ResourceThreads}; +use net_traits::image_cache::ImageCache; use profile_traits::mem as profile_mem; use profile_traits::time; use script_traits::{ConstellationControlMsg, DiscardBrowsingContext, ScriptToConstellationChan}; @@ -30,7 +30,7 @@ use script_traits::{NewLayoutInfo, SWManagerMsg, SWManagerSenders}; use script_traits::{ScriptThreadFactory, TimerSchedulerMsg, WindowSizeData}; use servo_channel::Sender; use servo_config::opts::{self, Opts}; -use servo_config::prefs::{Pref, PREFS}; +use servo_config::prefs::{PREFS, Pref}; use servo_url::ServoUrl; use std::collections::{HashMap, HashSet}; #[cfg(not(windows))] @@ -41,6 +41,7 @@ use std::rc::Rc; use std::sync::Arc; use style_traits::CSSPixel; use style_traits::DevicePixel; +use webrender_api; use webvr_traits::WebVRMsg; /// A `Pipeline` is the constellation's view of a `Document`. Each pipeline has an @@ -239,12 +240,10 @@ impl Pipeline { Err(e) => { error!("Cast to ScriptToDevtoolsControlMsg failed ({}).", e) }, - Ok(message) => { - if let Err(e) = - devtools_chan.send(DevtoolsControlMsg::FromScript(message)) - { - warn!("Sending to devtools failed ({:?})", e) - } + Ok(message) => if let Err(e) = + devtools_chan.send(DevtoolsControlMsg::FromScript(message)) + { + warn!("Sending to devtools failed ({:?})", e) }, }, ), @@ -431,7 +430,8 @@ impl Pipeline { /// Notify the script thread that this pipeline is visible. pub fn notify_visibility(&self, is_visible: bool) { - let script_msg = ConstellationControlMsg::ChangeFrameVisibilityStatus(self.id, is_visible); + let script_msg = + ConstellationControlMsg::ChangeFrameVisibilityStatus(self.id, is_visible); let compositor_msg = CompositorMsg::PipelineVisibilityChanged(self.id, is_visible); let err = self.event_loop.send(script_msg); if let Err(e) = err { @@ -517,7 +517,6 @@ impl UnprivilegedPipelineContent { webgl_chan: self.webgl_chan, webvr_chan: self.webvr_chan, webrender_document: self.webrender_document, - webrender_api_sender: self.webrender_api_sender.clone(), }, self.load_data.clone(), ); @@ -555,9 +554,9 @@ impl UnprivilegedPipelineContent { #[cfg(all(not(target_os = "windows"), not(target_os = "ios")))] pub fn spawn_multiprocess(self) -> Result<(), Error> { - use crate::sandboxing::content_process_sandbox_profile; use gaol::sandbox::{self, Sandbox, SandboxMethods}; use ipc_channel::ipc::IpcOneShotServer; + use sandboxing::content_process_sandbox_profile; impl CommandMethods for sandbox::Command { fn arg(&mut self, arg: T) diff --git a/components/constellation/session_history.rs b/components/constellation/session_history.rs index ae467432bf81..8faa09e75557 100644 --- a/components/constellation/session_history.rs +++ b/components/constellation/session_history.rs @@ -2,14 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::browsingcontext::NewBrowsingContextInfo; -use msg::constellation_msg::{ - BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, -}; +use browsingcontext::NewBrowsingContextInfo; +use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId}; use script_traits::LoadData; use servo_url::ServoUrl; -use std::cmp::PartialEq; use std::{fmt, mem}; +use std::cmp::PartialEq; /// Represents the joint session history /// https://html.spec.whatwg.org/multipage/#joint-session-history diff --git a/components/debugger/Cargo.toml b/components/debugger/Cargo.toml index 2c9b38a4a702..f03fd899332b 100644 --- a/components/debugger/Cargo.toml +++ b/components/debugger/Cargo.toml @@ -3,7 +3,6 @@ name = "debugger" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/debugger/lib.rs b/components/debugger/lib.rs index b61856631657..938e16906e3b 100644 --- a/components/debugger/lib.rs +++ b/components/debugger/lib.rs @@ -4,9 +4,11 @@ #[macro_use] extern crate log; +extern crate servo_channel; +extern crate ws; use std::thread; -use ws::{self, Builder, CloseCode, Handler, Handshake}; +use ws::{Builder, CloseCode, Handler, Handshake}; enum Message { ShutdownServer, @@ -47,8 +49,7 @@ pub fn start_server(port: u16) -> Sender { .name("debugger-websocket".to_owned()) .spawn(move || { socket.listen(("127.0.0.1", port)).unwrap(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); while let Some(message) = receiver.recv() { match message { Message::ShutdownServer => { @@ -57,8 +58,7 @@ pub fn start_server(port: u16) -> Sender { } } sender.shutdown().unwrap(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); Sender(sender) } diff --git a/components/deny_public_fields/Cargo.toml b/components/deny_public_fields/Cargo.toml index bc396ee720ac..f1637cf48e40 100644 --- a/components/deny_public_fields/Cargo.toml +++ b/components/deny_public_fields/Cargo.toml @@ -3,7 +3,6 @@ name = "deny_public_fields" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/deny_public_fields/lib.rs b/components/deny_public_fields/lib.rs index 4c4d913096d4..28fbf85add03 100644 --- a/components/deny_public_fields/lib.rs +++ b/components/deny_public_fields/lib.rs @@ -3,9 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate proc_macro; +extern crate syn; +#[macro_use] +extern crate synstructure; use std::str::FromStr; -use synstructure::{self, decl_derive}; decl_derive!([DenyPublicFields] => deny_public_fields_derive); diff --git a/components/devtools/Cargo.toml b/components/devtools/Cargo.toml index 706550068ffd..1bcbc1290b20 100644 --- a/components/devtools/Cargo.toml +++ b/components/devtools/Cargo.toml @@ -3,7 +3,6 @@ name = "devtools" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -12,11 +11,8 @@ path = "lib.rs" [dependencies] devtools_traits = {path = "../devtools_traits"} -headers-core = "0.0.1" -headers-ext = "0.0.3" -http = "0.1" -hyper = "0.12" -hyper_serde = "0.9" +hyper = "0.10" +hyper_serde = "0.8" ipc-channel = "0.11" log = "0.4" msg = {path = "../msg"} diff --git a/components/devtools/actor.rs b/components/devtools/actor.rs index 73180a784ed0..634622a20688 100644 --- a/components/devtools/actor.rs +++ b/components/devtools/actor.rs @@ -33,23 +33,23 @@ pub trait Actor: Any + ActorAsAny { } pub trait ActorAsAny { - fn actor_as_any(&self) -> &dyn Any; - fn actor_as_any_mut(&mut self) -> &mut dyn Any; + fn actor_as_any(&self) -> &Any; + fn actor_as_any_mut(&mut self) -> &mut Any; } impl ActorAsAny for T { - fn actor_as_any(&self) -> &dyn Any { + fn actor_as_any(&self) -> &Any { self } - fn actor_as_any_mut(&mut self) -> &mut dyn Any { + fn actor_as_any_mut(&mut self) -> &mut Any { self } } /// A list of known, owned actors. pub struct ActorRegistry { - actors: HashMap>, - new_actors: RefCell>>, + actors: HashMap>, + new_actors: RefCell>>, old_actors: RefCell>, script_actors: RefCell>, shareable: Option>>, @@ -131,11 +131,11 @@ impl ActorRegistry { } /// Add an actor to the registry of known actors that can receive messages. - pub fn register(&mut self, actor: Box) { + pub fn register(&mut self, actor: Box) { self.actors.insert(actor.name(), actor); } - pub fn register_later(&self, actor: Box) { + pub fn register_later(&self, actor: Box) { let mut actors = self.new_actors.borrow_mut(); actors.push(actor); } diff --git a/components/devtools/actors/browsing_context.rs b/components/devtools/actors/browsing_context.rs deleted file mode 100644 index 2d332c51f43b..000000000000 --- a/components/devtools/actors/browsing_context.rs +++ /dev/null @@ -1,205 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//! Liberally derived from the [Firefox JS implementation] -//! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). -//! Connection point for remote devtools that wish to investigate a particular Browsing Context's contents. -//! Supports dynamic attaching and detaching which control notifications of navigation, etc. - -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::actors::console::ConsoleActor; -use crate::protocol::JsonPacketStream; -use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; -use serde_json::{Map, Value}; -use std::net::TcpStream; - -#[derive(Serialize)] -struct BrowsingContextTraits; - -#[derive(Serialize)] -struct BrowsingContextAttachedReply { - from: String, - #[serde(rename = "type")] - type_: String, - threadActor: String, - cacheDisabled: bool, - javascriptEnabled: bool, - traits: BrowsingContextTraits, -} - -#[derive(Serialize)] -struct BrowsingContextDetachedReply { - from: String, - #[serde(rename = "type")] - type_: String, -} - -#[derive(Serialize)] -struct ReconfigureReply { - from: String, -} - -#[derive(Serialize)] -struct ListFramesReply { - from: String, - frames: Vec, -} - -#[derive(Serialize)] -struct FrameMsg { - id: u32, - url: String, - title: String, - parentID: u32, -} - -#[derive(Serialize)] -struct ListWorkersReply { - from: String, - workers: Vec, -} - -#[derive(Serialize)] -struct WorkerMsg { - id: u32, -} - -#[derive(Serialize)] -pub struct BrowsingContextActorMsg { - actor: String, - title: String, - url: String, - outerWindowID: u32, - consoleActor: String, - emulationActor: String, - inspectorActor: String, - timelineActor: String, - profilerActor: String, - performanceActor: String, - styleSheetsActor: String, -} - -pub struct BrowsingContextActor { - pub name: String, - pub title: String, - pub url: String, - pub console: String, - pub emulation: String, - pub inspector: String, - pub timeline: String, - pub profiler: String, - pub performance: String, - pub styleSheets: String, - pub thread: String, -} - -impl Actor for BrowsingContextActor { - fn name(&self) -> String { - self.name.clone() - } - - fn handle_message( - &self, - registry: &ActorRegistry, - msg_type: &str, - msg: &Map, - stream: &mut TcpStream, - ) -> Result { - Ok(match msg_type { - "reconfigure" => { - if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { - if let Some(val) = options.get("performReload") { - if val.as_bool().unwrap_or(false) { - let console_actor = registry.find::(&self.console); - let _ = console_actor - .script_chan - .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); - } - } - } - stream.write_json_packet(&ReconfigureReply { from: self.name() }); - ActorMessageStatus::Processed - }, - - // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs - // (see "To attach to a _targetActor_") - "attach" => { - let msg = BrowsingContextAttachedReply { - from: self.name(), - type_: "targetAttached".to_owned(), - threadActor: self.thread.clone(), - cacheDisabled: false, - javascriptEnabled: true, - traits: BrowsingContextTraits, - }; - let console_actor = registry.find::(&self.console); - console_actor - .streams - .borrow_mut() - .push(stream.try_clone().unwrap()); - stream.write_json_packet(&msg); - console_actor - .script_chan - .send(WantsLiveNotifications(console_actor.pipeline, true)) - .unwrap(); - ActorMessageStatus::Processed - }, - - //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 - // that the correct stream is removed. - "detach" => { - let msg = BrowsingContextDetachedReply { - from: self.name(), - type_: "detached".to_owned(), - }; - let console_actor = registry.find::(&self.console); - console_actor.streams.borrow_mut().pop(); - stream.write_json_packet(&msg); - console_actor - .script_chan - .send(WantsLiveNotifications(console_actor.pipeline, false)) - .unwrap(); - ActorMessageStatus::Processed - }, - - "listFrames" => { - let msg = ListFramesReply { - from: self.name(), - frames: vec![], - }; - stream.write_json_packet(&msg); - ActorMessageStatus::Processed - }, - - "listWorkers" => { - let msg = ListWorkersReply { - from: self.name(), - workers: vec![], - }; - stream.write_json_packet(&msg); - ActorMessageStatus::Processed - }, - - _ => ActorMessageStatus::Ignored, - }) - } -} - -impl BrowsingContextActor { - pub fn encodable(&self) -> BrowsingContextActorMsg { - BrowsingContextActorMsg { - actor: self.name(), - title: self.title.clone(), - url: self.url.clone(), - outerWindowID: 0, //FIXME: this should probably be the pipeline id - consoleActor: self.console.clone(), - emulationActor: self.emulation.clone(), - inspectorActor: self.inspector.clone(), - timelineActor: self.timeline.clone(), - profilerActor: self.profiler.clone(), - performanceActor: self.performance.clone(), - styleSheetsActor: self.styleSheets.clone(), - } - } -} diff --git a/components/devtools/actors/console.rs b/components/devtools/actors/console.rs index f2841d86f278..e19965701643 100644 --- a/components/devtools/actors/console.rs +++ b/components/devtools/actors/console.rs @@ -7,15 +7,15 @@ //! Mediates interaction between the remote web console and equivalent functionality (object //! inspection, JS evaluation, autocompletion) in Servo. -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::actors::object::ObjectActor; -use crate::protocol::JsonPacketStream; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actors::object::ObjectActor; +use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg}; use devtools_traits::CachedConsoleMessage; use devtools_traits::EvaluateJSReply::{ActorValue, BooleanValue, StringValue}; use devtools_traits::EvaluateJSReply::{NullValue, NumberValue, VoidValue}; -use devtools_traits::{CachedConsoleMessageTypes, DevtoolScriptControlMsg}; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::PipelineId; +use protocol::JsonPacketStream; use serde_json::{self, Map, Number, Value}; use std::cell::RefCell; use std::net::TcpStream; @@ -126,8 +126,7 @@ impl Actor for ConsoleActor { self.pipeline, message_types, chan, - )) - .unwrap(); + )).unwrap(); let messages = port .recv() .map_err(|_| ())? @@ -136,8 +135,7 @@ impl Actor for ConsoleActor { let json_string = message.encode().unwrap(); let json = serde_json::from_str::(&json_string).unwrap(); json.as_object().unwrap().to_owned() - }) - .collect(); + }).collect(); let msg = GetCachedMessagesReply { from: self.name(), @@ -198,8 +196,7 @@ impl Actor for ConsoleActor { self.pipeline, input.clone(), chan, - )) - .unwrap(); + )).unwrap(); //TODO: extract conversion into protocol module or some other useful place let result = match port.recv().map_err(|_| ())? { diff --git a/components/devtools/actors/device.rs b/components/devtools/actors/device.rs deleted file mode 100644 index 93f87168d09c..000000000000 --- a/components/devtools/actors/device.rs +++ /dev/null @@ -1,83 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::JsonPacketStream; -use crate::protocol::{ActorDescription, Method}; -use serde_json::{Map, Value}; -use std::net::TcpStream; - -#[derive(Serialize)] -struct GetDescriptionReply { - from: String, - value: SystemInfo, -} - -#[derive(Serialize)] -struct SystemInfo { - apptype: String, - platformVersion: String, -} - -pub struct DeviceActor { - pub name: String, -} - -impl Actor for DeviceActor { - fn name(&self) -> String { - self.name.clone() - } - fn handle_message( - &self, - _registry: &ActorRegistry, - msg_type: &str, - _msg: &Map, - stream: &mut TcpStream, - ) -> Result { - Ok(match msg_type { - "getDescription" => { - let msg = GetDescriptionReply { - from: self.name(), - value: SystemInfo { - apptype: "servo".to_string(), - platformVersion: "63.0".to_string(), - }, - }; - stream.write_json_packet(&msg); - ActorMessageStatus::Processed - }, - - _ => ActorMessageStatus::Ignored, - }) - } -} - -impl DeviceActor { - pub fn new(name: String) -> DeviceActor { - DeviceActor { name: name } - } - - pub fn description() -> ActorDescription { - ActorDescription { - category: "actor", - typeName: "device", - methods: vec![Method { - name: "getDescription", - request: Value::Null, - response: Value::Object( - vec![( - "value".to_owned(), - Value::Object( - vec![("_retval".to_owned(), Value::String("json".to_owned()))] - .into_iter() - .collect(), - ), - )] - .into_iter() - .collect(), - ), - }], - } - } -} diff --git a/components/devtools/actors/emulation.rs b/components/devtools/actors/emulation.rs deleted file mode 100644 index bd905ad77c42..000000000000 --- a/components/devtools/actors/emulation.rs +++ /dev/null @@ -1,35 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use serde_json::{Map, Value}; -use std::net::TcpStream; - -pub struct EmulationActor { - pub name: String, -} - -impl Actor for EmulationActor { - fn name(&self) -> String { - self.name.clone() - } - - fn handle_message( - &self, - _registry: &ActorRegistry, - msg_type: &str, - _msg: &Map, - _stream: &mut TcpStream, - ) -> Result { - Ok(match msg_type { - _ => ActorMessageStatus::Ignored, - }) - } -} - -impl EmulationActor { - pub fn new(name: String) -> EmulationActor { - EmulationActor { name: name } - } -} diff --git a/components/devtools/actors/framerate.rs b/components/devtools/actors/framerate.rs index 1bd7f001a476..56145c63620b 100644 --- a/components/devtools/actors/framerate.rs +++ b/components/devtools/actors/framerate.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::actors::timeline::HighResolutionStamp; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actors::timeline::HighResolutionStamp; use devtools_traits::DevtoolScriptControlMsg; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; diff --git a/components/devtools/actors/inspector.rs b/components/devtools/actors/inspector.rs index b18e2647f61c..040ba3421559 100644 --- a/components/devtools/actors/inspector.rs +++ b/components/devtools/actors/inspector.rs @@ -5,13 +5,13 @@ //! Liberally derived from the [Firefox JS implementation] //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/inspector.js). -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::JsonPacketStream; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use devtools_traits::{ComputedNodeLayout, DevtoolScriptControlMsg, NodeInfo}; use devtools_traits::DevtoolScriptControlMsg::{GetChildren, GetDocumentElement, GetRootNode}; use devtools_traits::DevtoolScriptControlMsg::{GetLayout, ModifyAttribute}; -use devtools_traits::{ComputedNodeLayout, DevtoolScriptControlMsg, NodeInfo}; use ipc_channel::ipc::{self, IpcSender}; use msg::constellation_msg::PipelineId; +use protocol::JsonPacketStream; use serde_json::{self, Map, Value}; use std::cell::RefCell; use std::net::TcpStream; @@ -111,16 +111,14 @@ impl Actor for NodeActor { .iter() .map(|json_mod| { serde_json::from_str(&serde_json::to_string(json_mod).unwrap()).unwrap() - }) - .collect(); + }).collect(); self.script_chan .send(ModifyAttribute( self.pipeline, registry.actor_to_script(target.to_owned()), modifications, - )) - .unwrap(); + )).unwrap(); let reply = ModifyAttributeReply { from: self.name() }; stream.write_json_packet(&reply); ActorMessageStatus::Processed @@ -230,8 +228,7 @@ impl NodeInfoToProtocol for NodeInfo { namespace: attr.namespace, name: attr.name, value: attr.value, - }) - .collect(), + }).collect(), pseudoClassLocks: vec![], //TODO get this data from script @@ -327,8 +324,7 @@ impl Actor for WalkerActor { self.pipeline, registry.actor_to_script(target.to_owned()), tx, - )) - .unwrap(); + )).unwrap(); let children = rx.recv().unwrap().ok_or(())?; let msg = ChildrenReply { @@ -338,8 +334,7 @@ impl Actor for WalkerActor { .into_iter() .map(|child| { child.encode(registry, true, self.script_chan.clone(), self.pipeline) - }) - .collect(), + }).collect(), from: self.name(), }; stream.write_json_packet(&msg); @@ -503,8 +498,7 @@ impl Actor for PageStyleActor { self.pipeline, registry.actor_to_script(target.to_owned()), tx, - )) - .unwrap(); + )).unwrap(); let ComputedNodeLayout { display, position, diff --git a/components/devtools/actors/memory.rs b/components/devtools/actors/memory.rs index 7c0da364106b..b88b5a3cf20d 100644 --- a/components/devtools/actors/memory.rs +++ b/components/devtools/actors/memory.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; use serde_json::{Map, Value}; use std::net::TcpStream; diff --git a/components/devtools/actors/network_event.rs b/components/devtools/actors/network_event.rs index e26ed49be30d..5e4fe01bcf32 100644 --- a/components/devtools/actors/network_event.rs +++ b/components/devtools/actors/network_event.rs @@ -6,22 +6,24 @@ //! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webconsole.js). //! Handles interaction with the remote web console on network events (HTTP requests, responses) in Servo. -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::JsonPacketStream; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; use devtools_traits::HttpRequest as DevtoolsHttpRequest; use devtools_traits::HttpResponse as DevtoolsHttpResponse; -use headers_core::HeaderMapExt; -use headers_ext::{ContentType, Cookie}; -use http::{header, HeaderMap}; -use hyper::{Method, StatusCode}; +use hyper::header::{ContentType, Cookie}; +use hyper::header::Headers; +use hyper::http::RawStatus; +use hyper::method::Method; +use protocol::JsonPacketStream; use serde_json::{Map, Value}; +use std::borrow::Cow; use std::net::TcpStream; +use time; use time::Tm; struct HttpRequest { url: String, method: Method, - headers: HeaderMap, + headers: Headers, body: Option>, startedDateTime: Tm, timeStamp: i64, @@ -30,8 +32,8 @@ struct HttpRequest { } struct HttpResponse { - headers: Option, - status: Option<(StatusCode, String)>, + headers: Option, + status: Option, body: Option>, } @@ -187,12 +189,13 @@ impl Actor for NetworkEventActor { let mut headers = Vec::new(); let mut rawHeadersString = "".to_owned(); let mut headersSize = 0; - for (name, value) in self.request.headers.iter() { - let value = &value.to_str().unwrap().to_string(); - rawHeadersString = rawHeadersString + name.as_str() + ":" + &value + "\r\n"; - headersSize += name.as_str().len() + value.len(); + for item in self.request.headers.iter() { + let name = item.name(); + let value = item.value_string(); + rawHeadersString = rawHeadersString + name + ":" + &value + "\r\n"; + headersSize += name.len() + value.len(); headers.push(Header { - name: name.as_str().to_owned(), + name: name.to_owned(), value: value.to_owned(), }); } @@ -207,10 +210,11 @@ impl Actor for NetworkEventActor { }, "getRequestCookies" => { let mut cookies = Vec::new(); - - for cookie in self.request.headers.get_all(header::COOKIE) { - if let Ok(cookie_value) = String::from_utf8(cookie.as_bytes().to_vec()) { - cookies = cookie_value.into_bytes(); + if let Some(req_cookies) = self.request.headers.get_raw("Cookie") { + for cookie in &*req_cookies { + if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { + cookies = cookie_value.into_bytes(); + } } } @@ -235,15 +239,17 @@ impl Actor for NetworkEventActor { let mut headers = vec![]; let mut rawHeadersString = "".to_owned(); let mut headersSize = 0; - for (name, value) in response_headers.iter() { + for item in response_headers.iter() { + let name = item.name(); + let value = item.value_string(); headers.push(Header { - name: name.as_str().to_owned(), - value: value.to_str().unwrap().to_owned(), + name: name.to_owned(), + value: value.clone(), }); - headersSize += name.as_str().len() + value.len(); - rawHeadersString.push_str(name.as_str()); + headersSize += name.len() + value.len(); + rawHeadersString.push_str(name); rawHeadersString.push_str(":"); - rawHeadersString.push_str(value.to_str().unwrap()); + rawHeadersString.push_str(&value); rawHeadersString.push_str("\r\n"); } let msg = GetResponseHeadersReply { @@ -258,10 +264,11 @@ impl Actor for NetworkEventActor { }, "getResponseCookies" => { let mut cookies = Vec::new(); - // TODO: This seems quite broken - for cookie in self.request.headers.get_all(header::SET_COOKIE) { - if let Ok(cookie_value) = String::from_utf8(cookie.as_bytes().to_vec()) { - cookies = cookie_value.into_bytes(); + if let Some(res_cookies) = self.request.headers.get_raw("set-cookie") { + for cookie in &*res_cookies { + if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { + cookies = cookie_value.into_bytes(); + } } } @@ -323,8 +330,8 @@ impl NetworkEventActor { name: name, request: HttpRequest { url: String::new(), - method: Method::GET, - headers: HeaderMap::new(), + method: Method::Get, + headers: Headers::new(), body: None, startedDateTime: time::now(), timeStamp: time::get_time().sec, @@ -356,7 +363,7 @@ impl NetworkEventActor { self.response.headers = response.headers.clone(); self.response.status = response.status.as_ref().map(|&(s, ref st)| { let status_text = String::from_utf8_lossy(st).into_owned(); - (StatusCode::from_u16(s).unwrap(), status_text) + RawStatus(s, Cow::from(status_text)) }); self.response.body = response.body.clone(); } @@ -382,8 +389,8 @@ impl NetworkEventActor { .response .status .as_ref() - .map_or((0, "".to_owned()), |(code, text)| { - (code.as_u16(), text.clone()) + .map_or((0, "".to_owned()), |&RawStatus(ref code, ref text)| { + (*code, text.clone().into_owned()) }); // TODO: Send the correct values for remoteAddress and remotePort and http_version. ResponseStartMsg { @@ -400,9 +407,9 @@ impl NetworkEventActor { pub fn response_content(&self) -> ResponseContentMsg { let mut mString = "".to_owned(); if let Some(ref headers) = self.response.headers { - mString = match headers.typed_get::() { - Some(ct) => ct.to_string(), - _ => "".to_owned(), + mString = match headers.get() { + Some(&ContentType(ref mime)) => mime.to_string(), + None => "".to_owned(), }; } // TODO: Set correct values when response's body is sent to the devtools in http_loader. @@ -417,9 +424,9 @@ impl NetworkEventActor { pub fn response_cookies(&self) -> ResponseCookiesMsg { let mut cookies_size = 0; if let Some(ref headers) = self.response.headers { - cookies_size = match headers.typed_get::() { - Some(ref cookie) => cookie.len(), - _ => 0, + cookies_size = match headers.get() { + Some(&Cookie(ref cookie)) => cookie.len(), + None => 0, }; } ResponseCookiesMsg { @@ -432,8 +439,8 @@ impl NetworkEventActor { let mut headers_byte_count = 0; if let Some(ref headers) = self.response.headers { headers_size = headers.len(); - for (name, value) in headers.iter() { - headers_byte_count += name.as_str().len() + value.len(); + for item in headers.iter() { + headers_byte_count += item.name().len() + item.value_string().len(); } } ResponseHeadersMsg { @@ -443,9 +450,11 @@ impl NetworkEventActor { } pub fn request_headers(&self) -> RequestHeadersMsg { - let size = self.request.headers.iter().fold(0, |acc, (name, value)| { - acc + name.as_str().len() + value.len() - }); + let size = self + .request + .headers + .iter() + .fold(0, |acc, h| acc + h.name().len() + h.value_string().len()); RequestHeadersMsg { headers: self.request.headers.len(), headersSize: size, @@ -453,9 +462,9 @@ impl NetworkEventActor { } pub fn request_cookies(&self) -> RequestCookiesMsg { - let cookies_size = match self.request.headers.typed_get::() { - Some(ref cookie) => cookie.len(), - _ => 0, + let cookies_size = match self.request.headers.get() { + Some(&Cookie(ref cookie)) => cookie.len(), + None => 0, }; RequestCookiesMsg { cookies: cookies_size, diff --git a/components/devtools/actors/object.rs b/components/devtools/actors/object.rs index 8699f6e3be06..0ed2facf848c 100644 --- a/components/devtools/actors/object.rs +++ b/components/devtools/actors/object.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; use serde_json::{Map, Value}; use std::net::TcpStream; diff --git a/components/devtools/actors/performance.rs b/components/devtools/actors/performance.rs index c68b04f93aaf..b3f367958a64 100644 --- a/components/devtools/actors/performance.rs +++ b/components/devtools/actors/performance.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::{ActorDescription, JsonPacketStream, Method}; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use protocol::{ActorDescription, JsonPacketStream, Method}; use serde_json::{Map, Value}; use std::net::TcpStream; @@ -106,8 +106,7 @@ impl PerformanceActor { vec![( "type".to_owned(), Value::String("canCurrentlyRecord".to_owned()), - )] - .into_iter() + )].into_iter() .collect(), ), response: Value::Object( @@ -118,8 +117,7 @@ impl PerformanceActor { .into_iter() .collect(), ), - )] - .into_iter() + )].into_iter() .collect(), ), }], diff --git a/components/devtools/actors/profiler.rs b/components/devtools/actors/profiler.rs index bc94b2875957..cb19f7afb6bc 100644 --- a/components/devtools/actors/profiler.rs +++ b/components/devtools/actors/profiler.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; use serde_json::{Map, Value}; use std::net::TcpStream; diff --git a/components/devtools/actors/root.rs b/components/devtools/actors/root.rs index 991b8c25e435..4e12055ec8eb 100644 --- a/components/devtools/actors/root.rs +++ b/components/devtools/actors/root.rs @@ -5,12 +5,11 @@ /// Liberally derived from the [Firefox JS implementation] /// (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/root.js). /// Connection point for all new remote devtools interactions, providing lists of know actors -/// that perform more specific actions (targets, addons, browser chrome, etc.) -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::actors::browsing_context::{BrowsingContextActor, BrowsingContextActorMsg}; -use crate::actors::device::DeviceActor; -use crate::actors::performance::PerformanceActor; -use crate::protocol::{ActorDescription, JsonPacketStream}; +/// that perform more specific actions (tabs, addons, browser chrome, etc.) +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actors::performance::PerformanceActor; +use actors::tab::{TabActor, TabActorMsg}; +use protocol::{ActorDescription, JsonPacketStream}; use serde_json::{Map, Value}; use std::net::TcpStream; @@ -31,19 +30,11 @@ struct ListAddonsReply { #[derive(Serialize)] enum AddonMsg {} -#[derive(Serialize)] -struct GetRootReply { - from: String, - selected: u32, - performanceActor: String, - deviceActor: String, -} - #[derive(Serialize)] struct ListTabsReply { from: String, selected: u32, - tabs: Vec, + tabs: Vec, } #[derive(Serialize)] @@ -62,13 +53,10 @@ pub struct ProtocolDescriptionReply { #[derive(Serialize)] pub struct Types { performance: ActorDescription, - device: ActorDescription, } pub struct RootActor { pub tabs: Vec, - pub performance: String, - pub device: String, } impl Actor for RootActor { @@ -93,18 +81,7 @@ impl Actor for RootActor { ActorMessageStatus::Processed }, - "getRoot" => { - let actor = GetRootReply { - from: "root".to_owned(), - selected: 0, - performanceActor: self.performance.clone(), - deviceActor: self.device.clone(), - }; - stream.write_json_packet(&actor); - ActorMessageStatus::Processed - }, - - // https://docs.firefox-dev.tools/backend/protocol.html#listing-browser-tabs + //https://wiki.mozilla.org/Remote_Debugging_Protocol#Listing_Browser_Tabs "listTabs" => { let actor = ListTabsReply { from: "root".to_owned(), @@ -112,7 +89,7 @@ impl Actor for RootActor { tabs: self .tabs .iter() - .map(|target| registry.find::(target).encodable()) + .map(|tab| registry.find::(tab).encodable()) .collect(), }; stream.write_json_packet(&actor); @@ -124,7 +101,6 @@ impl Actor for RootActor { from: self.name(), types: Types { performance: PerformanceActor::description(), - device: DeviceActor::description(), }, }; stream.write_json_packet(&msg); diff --git a/components/devtools/actors/stylesheets.rs b/components/devtools/actors/stylesheets.rs deleted file mode 100644 index e4f1858f31b4..000000000000 --- a/components/devtools/actors/stylesheets.rs +++ /dev/null @@ -1,32 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use serde_json::{Map, Value}; -use std::net::TcpStream; - -pub struct StyleSheetsActor { - pub name: String, -} - -impl Actor for StyleSheetsActor { - fn name(&self) -> String { - self.name.clone() - } - fn handle_message( - &self, - _: &ActorRegistry, - _: &str, - _: &Map, - _: &mut TcpStream, - ) -> Result { - Ok(ActorMessageStatus::Ignored) - } -} - -impl StyleSheetsActor { - pub fn new(name: String) -> StyleSheetsActor { - StyleSheetsActor { name: name } - } -} diff --git a/components/devtools/actors/tab.rs b/components/devtools/actors/tab.rs new file mode 100644 index 000000000000..e6f50773f689 --- /dev/null +++ b/components/devtools/actors/tab.rs @@ -0,0 +1,179 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +//! Liberally derived from the [Firefox JS implementation] +//! (http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/webbrowser.js). +//! Connection point for remote devtools that wish to investigate a particular tab's contents. +//! Supports dynamic attaching and detaching which control notifications of navigation, etc. + +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actors::console::ConsoleActor; +use devtools_traits::DevtoolScriptControlMsg::{self, WantsLiveNotifications}; +use protocol::JsonPacketStream; +use serde_json::{Map, Value}; +use std::net::TcpStream; + +#[derive(Serialize)] +struct TabTraits; + +#[derive(Serialize)] +struct TabAttachedReply { + from: String, + #[serde(rename = "type")] + type_: String, + threadActor: String, + cacheDisabled: bool, + javascriptEnabled: bool, + traits: TabTraits, +} + +#[derive(Serialize)] +struct TabDetachedReply { + from: String, + #[serde(rename = "type")] + type_: String, +} + +#[derive(Serialize)] +struct ReconfigureReply { + from: String, +} + +#[derive(Serialize)] +struct ListFramesReply { + from: String, + frames: Vec, +} + +#[derive(Serialize)] +struct FrameMsg { + id: u32, + url: String, + title: String, + parentID: u32, +} + +#[derive(Serialize)] +pub struct TabActorMsg { + actor: String, + title: String, + url: String, + outerWindowID: u32, + consoleActor: String, + inspectorActor: String, + timelineActor: String, + profilerActor: String, + performanceActor: String, +} + +pub struct TabActor { + pub name: String, + pub title: String, + pub url: String, + pub console: String, + pub inspector: String, + pub timeline: String, + pub profiler: String, + pub performance: String, + pub thread: String, +} + +impl Actor for TabActor { + fn name(&self) -> String { + self.name.clone() + } + + fn handle_message( + &self, + registry: &ActorRegistry, + msg_type: &str, + msg: &Map, + stream: &mut TcpStream, + ) -> Result { + Ok(match msg_type { + "reconfigure" => { + if let Some(options) = msg.get("options").and_then(|o| o.as_object()) { + if let Some(val) = options.get("performReload") { + if val.as_bool().unwrap_or(false) { + let console_actor = registry.find::(&self.console); + let _ = console_actor + .script_chan + .send(DevtoolScriptControlMsg::Reload(console_actor.pipeline)); + } + } + } + stream.write_json_packet(&ReconfigureReply { from: self.name() }); + ActorMessageStatus::Processed + }, + + // https://wiki.mozilla.org/Remote_Debugging_Protocol#Listing_Browser_Tabs + // (see "To attach to a _tabActor_") + "attach" => { + let msg = TabAttachedReply { + from: self.name(), + type_: "tabAttached".to_owned(), + threadActor: self.thread.clone(), + cacheDisabled: false, + javascriptEnabled: true, + traits: TabTraits, + }; + let console_actor = registry.find::(&self.console); + console_actor + .streams + .borrow_mut() + .push(stream.try_clone().unwrap()); + stream.write_json_packet(&msg); + console_actor + .script_chan + .send(WantsLiveNotifications(console_actor.pipeline, true)) + .unwrap(); + ActorMessageStatus::Processed + }, + + //FIXME: The current implementation won't work for multiple connections. Need to ensure 105 + // that the correct stream is removed. + "detach" => { + let msg = TabDetachedReply { + from: self.name(), + type_: "detached".to_owned(), + }; + let console_actor = registry.find::(&self.console); + console_actor.streams.borrow_mut().pop(); + stream.write_json_packet(&msg); + console_actor + .script_chan + .send(WantsLiveNotifications(console_actor.pipeline, false)) + .unwrap(); + ActorMessageStatus::Processed + }, + + "listFrames" => { + let msg = ListFramesReply { + from: self.name(), + frames: vec![], + }; + stream.write_json_packet(&msg); + ActorMessageStatus::Processed + }, + + _ => ActorMessageStatus::Ignored, + }) + } +} + +impl TabActor { + pub fn encodable(&self) -> TabActorMsg { + TabActorMsg { + actor: self.name(), + title: self.title.clone(), + url: self.url.clone(), + outerWindowID: 0, //FIXME: this should probably be the pipeline id + consoleActor: self.console.clone(), + inspectorActor: self.inspector.clone(), + timelineActor: self.timeline.clone(), + profilerActor: self.profiler.clone(), + performanceActor: self.performance.clone(), + } + } +} diff --git a/components/devtools/actors/thread.rs b/components/devtools/actors/thread.rs index 7cdb5229979a..dc2638bd1354 100644 --- a/components/devtools/actors/thread.rs +++ b/components/devtools/actors/thread.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::protocol::JsonPacketStream; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use protocol::JsonPacketStream; use serde_json::{Map, Value}; use std::net::TcpStream; @@ -33,13 +33,6 @@ struct ThreadResumedReply { type_: String, } -#[derive(Serialize)] -struct ThreadInterruptedReply { - from: String, - #[serde(rename = "type")] - type_: String, -} - #[derive(Serialize)] struct ReconfigureReply { from: String, @@ -100,15 +93,6 @@ impl Actor for ThreadActor { ActorMessageStatus::Processed }, - "interrupt" => { - let msg = ThreadInterruptedReply { - from: self.name(), - type_: "interrupted".to_owned(), - }; - stream.write_json_packet(&msg); - ActorMessageStatus::Processed - }, - "reconfigure" => { stream.write_json_packet(&ReconfigureReply { from: self.name() }); ActorMessageStatus::Processed diff --git a/components/devtools/actors/timeline.rs b/components/devtools/actors/timeline.rs index e1ad44d1ee5b..d5b5295a138d 100644 --- a/components/devtools/actors/timeline.rs +++ b/components/devtools/actors/timeline.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; -use crate::actors::framerate::FramerateActor; -use crate::actors::memory::{MemoryActor, TimelineMemoryReply}; -use crate::protocol::JsonPacketStream; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actors::framerate::FramerateActor; +use actors::memory::{MemoryActor, TimelineMemoryReply}; +use devtools_traits::{PreciseTime, TimelineMarker, TimelineMarkerType}; use devtools_traits::DevtoolScriptControlMsg; use devtools_traits::DevtoolScriptControlMsg::{DropTimelineMarkers, SetTimelineMarkers}; -use devtools_traits::{PreciseTime, TimelineMarker, TimelineMarkerType}; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use msg::constellation_msg::PipelineId; +use protocol::JsonPacketStream; use serde::{Serialize, Serializer}; use serde_json::{Map, Value}; use std::cell::RefCell; @@ -169,8 +169,7 @@ impl TimelineActor { emitter.send(markers); thread::sleep(Duration::from_millis(DEFAULT_TIMELINE_DATA_PULL_TIMEOUT)); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } } @@ -196,8 +195,7 @@ impl Actor for TimelineActor { self.pipeline, self.marker_types.clone(), tx, - )) - .unwrap(); + )).unwrap(); *self.stream.borrow_mut() = stream.try_clone().ok(); @@ -250,8 +248,7 @@ impl Actor for TimelineActor { .send(DropTimelineMarkers( self.pipeline, self.marker_types.clone(), - )) - .unwrap(); + )).unwrap(); if let Some(ref actor_name) = *self.framerate_actor.borrow() { registry.drop_actor_later(actor_name.clone()); diff --git a/components/devtools/actors/worker.rs b/components/devtools/actors/worker.rs index 186145a8f581..9ccc5b2e10bf 100644 --- a/components/devtools/actors/worker.rs +++ b/components/devtools/actors/worker.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::actor::{Actor, ActorMessageStatus, ActorRegistry}; +use actor::{Actor, ActorMessageStatus, ActorRegistry}; use devtools_traits::WorkerId; use serde_json::{Map, Value}; use std::net::TcpStream; diff --git a/components/devtools/lib.rs b/components/devtools/lib.rs index 0768a79ed09f..8bd34c0a1d06 100644 --- a/components/devtools/lib.rs +++ b/components/devtools/lib.rs @@ -12,37 +12,41 @@ #![allow(non_snake_case)] #![deny(unsafe_code)] +extern crate devtools_traits; +extern crate hyper; +extern crate ipc_channel; #[macro_use] extern crate log; +extern crate msg; #[macro_use] extern crate serde; - -use crate::actor::{Actor, ActorRegistry}; -use crate::actors::browsing_context::BrowsingContextActor; -use crate::actors::console::ConsoleActor; -use crate::actors::device::DeviceActor; -use crate::actors::emulation::EmulationActor; -use crate::actors::framerate::FramerateActor; -use crate::actors::inspector::InspectorActor; -use crate::actors::network_event::{EventActor, NetworkEventActor, ResponseStartMsg}; -use crate::actors::performance::PerformanceActor; -use crate::actors::profiler::ProfilerActor; -use crate::actors::root::RootActor; -use crate::actors::stylesheets::StyleSheetsActor; -use crate::actors::thread::ThreadActor; -use crate::actors::timeline::TimelineActor; -use crate::actors::worker::WorkerActor; -use crate::protocol::JsonPacketStream; +extern crate serde_json; +extern crate servo_channel; +extern crate time; + +use actor::{Actor, ActorRegistry}; +use actors::console::ConsoleActor; +use actors::framerate::FramerateActor; +use actors::inspector::InspectorActor; +use actors::network_event::{EventActor, NetworkEventActor, ResponseStartMsg}; +use actors::performance::PerformanceActor; +use actors::profiler::ProfilerActor; +use actors::root::RootActor; +use actors::tab::TabActor; +use actors::thread::ThreadActor; +use actors::timeline::TimelineActor; +use actors::worker::WorkerActor; use devtools_traits::{ChromeToDevtoolsControlMsg, ConsoleMessage, DevtoolsControlMsg}; use devtools_traits::{DevtoolScriptControlMsg, DevtoolsPageInfo, LogLevel, NetworkEvent}; use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use servo_channel::{channel, Receiver, Sender}; +use protocol::JsonPacketStream; +use servo_channel::{Receiver, Sender, channel}; use std::borrow::ToOwned; use std::cell::RefCell; -use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::net::{Shutdown, TcpListener, TcpStream}; use std::sync::{Arc, Mutex}; use std::thread; @@ -51,10 +55,7 @@ use time::precise_time_ns; mod actor; /// Corresponds to http://mxr.mozilla.org/mozilla-central/source/toolkit/devtools/server/actors/ mod actors { - pub mod browsing_context; pub mod console; - pub mod device; - pub mod emulation; pub mod framerate; pub mod inspector; pub mod memory; @@ -63,7 +64,7 @@ mod actors { pub mod performance; pub mod profiler; pub mod root; - pub mod stylesheets; + pub mod tab; pub mod thread; pub mod timeline; pub mod worker; @@ -145,19 +146,9 @@ fn run_server( let mut registry = ActorRegistry::new(); - let performance = PerformanceActor::new(registry.new_name("performance")); - - let device = DeviceActor::new(registry.new_name("device")); - - let root = Box::new(RootActor { - tabs: vec![], - device: device.name(), - performance: performance.name(), - }); + let root = Box::new(RootActor { tabs: vec![] }); registry.register(root); - registry.register(Box::new(performance)); - registry.register(Box::new(device)); registry.find::("root"); let actors = registry.create_shareable(); @@ -211,7 +202,7 @@ fn run_server( // We need separate actor representations for each script global that exists; // clients can theoretically connect to multiple globals simultaneously. - // TODO: move this into the root or target modules? + // TODO: move this into the root or tab modules? fn handle_new_global( actors: Arc>, ids: (PipelineId, Option), @@ -224,27 +215,14 @@ fn run_server( let (pipeline, worker_id) = ids; - //TODO: move all this actor creation into a constructor method on BrowsingContextActor - let ( - target, - console, - emulation, - inspector, - timeline, - profiler, - performance, - styleSheets, - thread, - ) = { + //TODO: move all this actor creation into a constructor method on TabActor + let (tab, console, inspector, timeline, profiler, performance, thread) = { let console = ConsoleActor { name: actors.new_name("console"), script_chan: script_sender.clone(), pipeline: pipeline, streams: RefCell::new(Vec::new()), }; - - let emulation = EmulationActor::new(actors.new_name("emulation")); - let inspector = InspectorActor { name: actors.new_name("inspector"), walker: RefCell::new(None), @@ -259,38 +237,31 @@ fn run_server( let profiler = ProfilerActor::new(actors.new_name("profiler")); let performance = PerformanceActor::new(actors.new_name("performance")); - // the strange switch between styleSheets and stylesheets is due - // to an inconsistency in devtools. See Bug #1498893 in bugzilla - let styleSheets = StyleSheetsActor::new(actors.new_name("stylesheets")); let thread = ThreadActor::new(actors.new_name("context")); let DevtoolsPageInfo { title, url } = page_info; - let target = BrowsingContextActor { - name: actors.new_name("target"), + let tab = TabActor { + name: actors.new_name("tab"), title: String::from(title), url: url.into_string(), console: console.name(), - emulation: emulation.name(), inspector: inspector.name(), timeline: timeline.name(), profiler: profiler.name(), performance: performance.name(), - styleSheets: styleSheets.name(), thread: thread.name(), }; let root = actors.find_mut::("root"); - root.tabs.push(target.name.clone()); + root.tabs.push(tab.name.clone()); ( - target, + tab, console, - emulation, inspector, timeline, profiler, performance, - styleSheets, thread, ) }; @@ -305,15 +276,13 @@ fn run_server( actors.register(Box::new(worker)); } - actor_pipelines.insert(pipeline, target.name.clone()); - actors.register(Box::new(target)); + actor_pipelines.insert(pipeline, tab.name.clone()); + actors.register(Box::new(tab)); actors.register(Box::new(console)); - actors.register(Box::new(emulation)); actors.register(Box::new(inspector)); actors.register(Box::new(timeline)); actors.register(Box::new(profiler)); actors.register(Box::new(performance)); - actors.register(Box::new(styleSheets)); actors.register(Box::new(thread)); } @@ -347,8 +316,7 @@ fn run_server( LogLevel::Warn => "warn", LogLevel::Error => "error", _ => "log", - } - .to_owned(), + }.to_owned(), timeStamp: precise_time_ns(), arguments: vec![console_message.message], filename: console_message.filename, @@ -374,12 +342,7 @@ fn run_server( Some(actors.find::(actor_name).console.clone()) } else { let actor_name = (*actor_pipelines).get(&id)?; - Some( - actors - .find::(actor_name) - .console - .clone(), - ) + Some(actors.find::(actor_name).console.clone()) } } @@ -543,11 +506,9 @@ fn run_server( sender_clone .send(DevtoolsControlMsg::FromChrome( ChromeToDevtoolsControlMsg::AddClient(stream.unwrap()), - )) - .unwrap(); + )).unwrap(); } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); while let Some(msg) = receiver.recv() { match msg { diff --git a/components/devtools_traits/Cargo.toml b/components/devtools_traits/Cargo.toml index f3a1868ff4ab..34359dadf41f 100644 --- a/components/devtools_traits/Cargo.toml +++ b/components/devtools_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "devtools_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -12,7 +11,8 @@ path = "lib.rs" [dependencies] bitflags = "1.0" -http = "0.1" +hyper = "0.10" +hyper_serde = "0.8" ipc-channel = "0.11" malloc_size_of = { path = "../malloc_size_of" } malloc_size_of_derive = { path = "../malloc_size_of_derive" } diff --git a/components/devtools_traits/lib.rs b/components/devtools_traits/lib.rs index e02803451693..764af5da0a27 100644 --- a/components/devtools_traits/lib.rs +++ b/components/devtools_traits/lib.rs @@ -13,18 +13,25 @@ #[macro_use] extern crate bitflags; +extern crate hyper; +extern crate ipc_channel; +extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; +extern crate msg; #[macro_use] extern crate serde; +extern crate servo_url; +extern crate time; -use http::method::Method; -use http::HeaderMap; +use hyper::header::Headers; +use hyper::method::Method; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; use servo_url::ServoUrl; use std::net::TcpStream; -use time::{self, Duration, Tm}; +use time::Duration; +use time::Tm; // Information would be attached to NewGlobal to be received and show in devtools. // Extend these fields if we need more information. @@ -294,7 +301,7 @@ pub enum CachedConsoleMessage { pub struct HttpRequest { pub url: ServoUrl, pub method: Method, - pub headers: HeaderMap, + pub headers: Headers, pub body: Option>, pub pipeline_id: PipelineId, pub startedDateTime: Tm, @@ -306,7 +313,7 @@ pub struct HttpRequest { #[derive(Debug, PartialEq)] pub struct HttpResponse { - pub headers: Option, + pub headers: Option, pub status: Option<(u16, Vec)>, pub body: Option>, pub pipeline_id: PipelineId, diff --git a/components/dom_struct/lib.rs b/components/dom_struct/lib.rs index 95d7b0446d5a..442aa6cf2cd6 100644 --- a/components/dom_struct/lib.rs +++ b/components/dom_struct/lib.rs @@ -3,6 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ extern crate proc_macro; + #[macro_use] extern crate quote; extern crate syn; @@ -46,7 +47,7 @@ pub fn dom_struct(args: TokenStream, input: TokenStream) -> TokenStream { quote! ( #s2 - impl crate::dom::bindings::inheritance::HasParent for #name { + impl ::dom::bindings::inheritance::HasParent for #name { type Parent = #ty; /// This is used in a type assertion to ensure that /// the source and webidls agree as to what the parent type is @@ -54,8 +55,7 @@ pub fn dom_struct(args: TokenStream, input: TokenStream) -> TokenStream { &self.#ident } } - ) - .into() + ).into() } else { panic!("#[dom_struct] only applies to structs with named fields"); } diff --git a/components/domobject_derive/Cargo.toml b/components/domobject_derive/Cargo.toml index 0ab7212cafec..80b6125bbab1 100644 --- a/components/domobject_derive/Cargo.toml +++ b/components/domobject_derive/Cargo.toml @@ -3,7 +3,6 @@ name = "domobject_derive" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/domobject_derive/lib.rs b/components/domobject_derive/lib.rs index 05308e53c653..7eff765b928a 100644 --- a/components/domobject_derive/lib.rs +++ b/components/domobject_derive/lib.rs @@ -41,22 +41,22 @@ fn expand_dom_object(input: syn::DeriveInput) -> quote::Tokens { impl #impl_generics ::js::conversions::ToJSValConvertible for #name #ty_generics #where_clause { #[allow(unsafe_code)] unsafe fn to_jsval(&self, - cx: *mut js::jsapi::JSContext, - rval: js::rust::MutableHandleValue) { - let object = crate::dom::bindings::reflector::DomObject::reflector(self).get_jsobject(); + cx: *mut ::js::jsapi::JSContext, + rval: ::js::rust::MutableHandleValue) { + let object = ::dom::bindings::reflector::DomObject::reflector(self).get_jsobject(); object.to_jsval(cx, rval) } } - impl #impl_generics crate::dom::bindings::reflector::DomObject for #name #ty_generics #where_clause { + impl #impl_generics ::dom::bindings::reflector::DomObject for #name #ty_generics #where_clause { #[inline] - fn reflector(&self) -> &crate::dom::bindings::reflector::Reflector { + fn reflector(&self) -> &::dom::bindings::reflector::Reflector { self.#first_field_name.reflector() } } - impl #impl_generics crate::dom::bindings::reflector::MutDomObject for #name #ty_generics #where_clause { - fn init_reflector(&mut self, obj: *mut js::jsapi::JSObject) { + impl #impl_generics ::dom::bindings::reflector::MutDomObject for #name #ty_generics #where_clause { + fn init_reflector(&mut self, obj: *mut ::js::jsapi::JSObject) { self.#first_field_name.init_reflector(obj); } } @@ -76,9 +76,9 @@ fn expand_dom_object(input: syn::DeriveInput) -> quote::Tokens { })); let mut generics = input.generics.clone(); - generics.params.push(parse_quote!( - __T: crate::dom::bindings::reflector::DomObject - )); + generics + .params + .push(parse_quote!(__T: ::dom::bindings::reflector::DomObject)); let (impl_generics, _, where_clause) = generics.split_for_impl(); diff --git a/components/embedder_traits/Cargo.toml b/components/embedder_traits/Cargo.toml index 68f2917e2c2d..da187d7d3700 100644 --- a/components/embedder_traits/Cargo.toml +++ b/components/embedder_traits/Cargo.toml @@ -3,21 +3,22 @@ name = "embedder_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] name = "embedder_traits" path = "lib.rs" +[features] +tests = [] + [dependencies] ipc-channel = "0.11" -keyboard-types = {version = "0.4.2-servo", features = ["serde"]} lazy_static = "1" log = "0.4" msg = {path = "../msg"} serde = "1.0" servo_channel = {path = "../channel"} servo_url = {path = "../url"} -style_traits = {path = "../style_traits", features = ["servo"]} +style_traits = {path = "../style_traits"} webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} diff --git a/components/embedder_traits/lib.rs b/components/embedder_traits/lib.rs index 96364c5e6390..6bb9281b7d23 100644 --- a/components/embedder_traits/lib.rs +++ b/components/embedder_traits/lib.rs @@ -2,18 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate ipc_channel; #[macro_use] extern crate lazy_static; #[macro_use] extern crate log; +extern crate msg; #[macro_use] extern crate serde; +extern crate servo_channel; +extern crate servo_url; +extern crate style_traits; +extern crate webrender_api; pub mod resources; use ipc_channel::ipc::IpcSender; -use keyboard_types::KeyboardEvent; -use msg::constellation_msg::{InputMethodType, TopLevelBrowsingContextId}; +use msg::constellation_msg::{InputMethodType, Key, KeyModifiers, KeyState, TopLevelBrowsingContextId}; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::fmt::{Debug, Error, Formatter}; @@ -88,7 +93,7 @@ pub enum EmbedderMsg { /// Wether or not to unload a document AllowUnload(IpcSender), /// Sends an unconsumed key event back to the embedder. - Keyboard(KeyboardEvent), + KeyEvent(Option, Key, KeyState, KeyModifiers), /// Changes the cursor. SetCursor(CursorKind), /// A favicon was detected @@ -129,7 +134,7 @@ impl Debug for EmbedderMsg { EmbedderMsg::Alert(..) => write!(f, "Alert"), EmbedderMsg::AllowUnload(..) => write!(f, "AllowUnload"), EmbedderMsg::AllowNavigation(..) => write!(f, "AllowNavigation"), - EmbedderMsg::Keyboard(..) => write!(f, "Keyboard"), + EmbedderMsg::KeyEvent(..) => write!(f, "KeyEvent"), EmbedderMsg::SetCursor(..) => write!(f, "SetCursor"), EmbedderMsg::NewFavicon(..) => write!(f, "NewFavicon"), EmbedderMsg::HeadParsed => write!(f, "HeadParsed"), diff --git a/components/embedder_traits/resources.rs b/components/embedder_traits/resources.rs index 9aebc11d06db..b38b36181a08 100644 --- a/components/embedder_traits/resources.rs +++ b/components/embedder_traits/resources.rs @@ -3,21 +3,25 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::path::PathBuf; -use std::sync::{Once, RwLock}; +use std::sync::RwLock; lazy_static! { - static ref RES: RwLock>> = RwLock::new(None); + static ref RES: RwLock>> = RwLock::new({ + #[cfg(not(feature = "tests"))] + { + None + } + #[cfg(feature = "tests")] + { + Some(resources_for_tests()) + } + }); } pub fn set(reader: Box) { *RES.write().unwrap() = Some(reader); } -pub fn set_for_tests() { - static ONCE: Once = Once::new(); - ONCE.call_once(|| set(resources_for_tests())); -} - pub fn read_bytes(res: Resource) -> Vec { RES.read() .unwrap() @@ -67,6 +71,7 @@ pub trait ResourceReaderMethods { fn sandbox_access_files_dirs(&self) -> Vec; } +#[cfg(feature = "tests")] fn resources_for_tests() -> Box { use std::env; use std::fs::File; diff --git a/components/fallible/lib.rs b/components/fallible/lib.rs index f807bc9ce7a6..ae6a40dc789d 100644 --- a/components/fallible/lib.rs +++ b/components/fallible/lib.rs @@ -5,9 +5,9 @@ extern crate hashglobe; extern crate smallvec; +use hashglobe::FailedAllocationError; #[cfg(feature = "known_system_malloc")] use hashglobe::alloc; -use hashglobe::FailedAllocationError; use smallvec::Array; use smallvec::SmallVec; use std::vec::Vec; diff --git a/components/geometry/Cargo.toml b/components/geometry/Cargo.toml index a88b601e562a..b9ad20b665d2 100644 --- a/components/geometry/Cargo.toml +++ b/components/geometry/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_geometry" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/geometry/lib.rs b/components/geometry/lib.rs index 654bf8b3c80f..2f421f6a277b 100644 --- a/components/geometry/lib.rs +++ b/components/geometry/lib.rs @@ -2,8 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate app_units; +extern crate euclid; +extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; +extern crate style_traits; +extern crate webrender_api; use app_units::{Au, MAX_AU, MIN_AU}; use euclid::{Length, Point2D, Rect, Size2D}; diff --git a/components/gfx/Cargo.toml b/components/gfx/Cargo.toml index 1932d2006269..2a09114f8f69 100644 --- a/components/gfx/Cargo.toml +++ b/components/gfx/Cargo.toml @@ -4,7 +4,6 @@ name = "gfx" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -38,7 +37,7 @@ servo_arc = {path = "../servo_arc"} servo_atoms = {path = "../atoms"} servo_url = {path = "../url"} smallvec = { version = "0.6", features = ["std", "union"] } -style = {path = "../style", features = ["servo"]} +style = {path = "../style"} time = "0.1.12" unicode-bidi = {version = "0.3", features = ["with_serde"]} unicode-script = {version = "0.2", features = ["harfbuzz"]} @@ -49,8 +48,8 @@ ucd = "0.1.1" [target.'cfg(target_os = "macos")'.dependencies] byteorder = "1.0" core-foundation = "0.6" -core-graphics = "0.17" -core-text = "13.0" +core-graphics = "0.16" +core-text = "11.0" [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] freetype = "0.4" @@ -63,5 +62,5 @@ servo-fontconfig = "0.2.1" xml5ever = {version = "0.12"} [target.'cfg(target_os = "windows")'.dependencies] -dwrote = "0.6" +dwrote = "0.4" truetype = "0.26" diff --git a/components/gfx/font.rs b/components/gfx/font.rs index 33ed7cd6d7f7..a3591e3b41a5 100644 --- a/components/gfx/font.rs +++ b/components/gfx/font.rs @@ -3,17 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use crate::font_context::{FontContext, FontSource}; -use crate::font_template::FontTemplateDescriptor; -use crate::platform::font::{FontHandle, FontTable}; -use crate::platform::font_context::FontContextHandle; -pub use crate::platform::font_list::fallback_font_families; -use crate::platform::font_template::FontTemplateData; -use crate::text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; -use crate::text::shaping::ShaperMethods; -use crate::text::Shaper; use euclid::{Point2D, Rect, Size2D}; +use font_context::{FontContext, FontSource}; +use font_template::FontTemplateDescriptor; use ordered_float::NotNan; +use platform::font::{FontHandle, FontTable}; +use platform::font_context::FontContextHandle; +pub use platform::font_list::fallback_font_families; +use platform::font_template::FontTemplateData; use servo_atoms::Atom; use smallvec::SmallVec; use std::borrow::ToOwned; @@ -22,12 +19,17 @@ use std::collections::HashMap; use std::iter; use std::rc::Rc; use std::str; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::sync::Arc; +use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; use style::computed_values::{font_stretch, font_style, font_variant_caps, font_weight}; use style::properties::style_structs::Font as FontStyleStruct; use style::values::computed::font::SingleFontFamily; +use text::Shaper; +use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; +use text::shaping::ShaperMethods; +use time; use unicode_script::Script; +use webrender_api; macro_rules! ot_tag { ($t1:expr, $t2:expr, $t3:expr, $t4:expr) => { @@ -62,13 +64,13 @@ pub trait FontHandleMethods: Sized { fn stretchiness(&self) -> font_stretch::T; fn glyph_index(&self, codepoint: char) -> Option; - fn glyph_h_advance(&self, _: GlyphId) -> Option; + fn glyph_h_advance(&self, GlyphId) -> Option; fn glyph_h_kerning(&self, glyph0: GlyphId, glyph1: GlyphId) -> FractionalPixel; /// Can this font do basic horizontal LTR shaping without Harfbuzz? fn can_do_fast_shaping(&self) -> bool; fn metrics(&self) -> FontMetrics; - fn table_for_tag(&self, _: FontTableTag) -> Option; + fn table_for_tag(&self, FontTableTag) -> Option; /// A unique identifier for the font, allowing comparison. fn identifier(&self) -> Atom; @@ -252,8 +254,7 @@ impl Font { TEXT_SHAPING_PERFORMANCE_COUNTER .fetch_add((end_time - start_time) as usize, Ordering::Relaxed); Arc::new(glyphs) - }) - .clone(); + }).clone(); self.shaper = shaper; result } @@ -449,8 +450,7 @@ impl FontGroup { iter::once(FontFamilyDescriptor::default()) .chain(fallback_font_families(codepoint).into_iter().map(|family| { FontFamilyDescriptor::new(FontFamilyName::from(family), FontSearchScope::Local) - })) - .filter_map(|family| font_context.font(&self.descriptor, &family)) + })).filter_map(|family| font_context.font(&self.descriptor, &family)) .find(predicate) } } diff --git a/components/gfx/font_cache_thread.rs b/components/gfx/font_cache_thread.rs index 0c769aeb71a1..4bfa3e6dfc25 100644 --- a/components/gfx/font_cache_thread.rs +++ b/components/gfx/font_cache_thread.rs @@ -3,27 +3,29 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use crate::font::{FontFamilyDescriptor, FontFamilyName, FontSearchScope}; -use crate::font_context::FontSource; -use crate::font_template::{FontTemplate, FontTemplateDescriptor}; -use crate::platform::font_context::FontContextHandle; -use crate::platform::font_list::for_each_available_family; -use crate::platform::font_list::for_each_variation; -use crate::platform::font_list::system_default_family; -use crate::platform::font_list::SANS_SERIF_FONT_FAMILY; -use crate::platform::font_template::FontTemplateData; +use font::{FontFamilyDescriptor, FontFamilyName, FontSearchScope}; +use font_context::FontSource; +use font_template::{FontTemplate, FontTemplateDescriptor}; +use fontsan; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; +use net_traits::{CoreResourceThread, FetchResponseMsg, fetch_async}; use net_traits::request::{Destination, RequestInit}; -use net_traits::{fetch_async, CoreResourceThread, FetchResponseMsg}; +use platform::font_context::FontContextHandle; +use platform::font_list::SANS_SERIF_FONT_FAMILY; +use platform::font_list::for_each_available_family; +use platform::font_list::for_each_variation; +use platform::font_list::system_default_family; +use platform::font_template::FontTemplateData; use servo_atoms::Atom; use servo_url::ServoUrl; +use std::{fmt, f32, mem, thread}; use std::borrow::ToOwned; use std::collections::HashMap; use std::ops::Deref; use std::sync::{Arc, Mutex}; -use std::{f32, fmt, mem, thread}; use style::font_face::{EffectiveSources, Source}; use style::values::computed::font::FamilyName; +use webrender_api; /// A list of font templates that make up a given font family. pub struct FontTemplates { @@ -432,8 +434,7 @@ impl FontCache { FontSearchScope::Local => { self.find_font_in_local_family(&template_descriptor, &family_descriptor.name) }, - } - .map(|t| self.get_font_template_info(t)) + }.map(|t| self.get_font_template_info(t)) } } @@ -473,8 +474,7 @@ impl FontCacheThread { cache.refresh_local_families(); cache.run(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); FontCacheThread { chan: chan } } @@ -490,8 +490,7 @@ impl FontCacheThread { LowercaseString::new(&family.name), sources, sender, - )) - .unwrap(); + )).unwrap(); } pub fn exit(&self) { @@ -539,8 +538,7 @@ impl FontSource for FontCacheThread { template_descriptor, family_descriptor, response_chan, - )) - .expect("failed to send message to font cache thread"); + )).expect("failed to send message to font cache thread"); let reply = response_port.recv(); diff --git a/components/gfx/font_context.rs b/components/gfx/font_context.rs index c90ce5437312..6cb4d8e7ed60 100644 --- a/components/gfx/font_context.rs +++ b/components/gfx/font_context.rs @@ -3,15 +3,13 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use crate::font::{ - Font, FontDescriptor, FontFamilyDescriptor, FontGroup, FontHandleMethods, FontRef, -}; -use crate::font_cache_thread::FontTemplateInfo; -use crate::font_template::FontTemplateDescriptor; -use crate::platform::font::FontHandle; -pub use crate::platform::font_context::FontContextHandle; use fnv::FnvHasher; +use font::{Font, FontDescriptor, FontFamilyDescriptor, FontGroup, FontHandleMethods, FontRef}; +use font_cache_thread::FontTemplateInfo; +use font_template::FontTemplateDescriptor; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; +use platform::font::FontHandle; +pub use platform::font_context::FontContextHandle; use servo_arc::Arc; use std::cell::RefCell; use std::collections::HashMap; @@ -21,6 +19,7 @@ use std::rc::Rc; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use style::computed_values::font_variant_caps::T as FontVariantCaps; use style::properties::style_structs::Font as FontStyleStruct; +use webrender_api; static SMALL_CAPS_SCALE_FACTOR: f32 = 0.8; // Matches FireFox (see gfxFont.h) @@ -134,8 +133,7 @@ impl FontContext { .and_then(|template_info| { self.create_font(template_info, font_descriptor.to_owned()) .ok() - }) - .map(|font| Rc::new(RefCell::new(font))); + }).map(|font| Rc::new(RefCell::new(font))); self.font_cache.insert(cache_key, font.clone()); font diff --git a/components/gfx/font_template.rs b/components/gfx/font_template.rs index 0285cfc9dde3..80527dfae388 100644 --- a/components/gfx/font_template.rs +++ b/components/gfx/font_template.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::font::FontHandleMethods; -use crate::platform::font::FontHandle; -use crate::platform::font_context::FontContextHandle; -use crate::platform::font_template::FontTemplateData; +use font::FontHandleMethods; +use platform::font::FontHandle; +use platform::font_context::FontContextHandle; +use platform::font_template::FontTemplateData; use servo_atoms::Atom; use std::fmt::{Debug, Error, Formatter}; use std::io::Error as IoError; diff --git a/components/gfx/lib.rs b/components/gfx/lib.rs index 24dbcde26cba..442a9c8ae3ad 100644 --- a/components/gfx/lib.rs +++ b/components/gfx/lib.rs @@ -4,16 +4,75 @@ #![deny(unsafe_code)] +extern crate app_units; #[macro_use] extern crate bitflags; + +// Mac OS-specific library dependencies +#[cfg(target_os = "macos")] +extern crate byteorder; +#[cfg(target_os = "macos")] +extern crate core_foundation; +#[cfg(target_os = "macos")] +extern crate core_graphics; +#[cfg(target_os = "macos")] +extern crate core_text; + +// Windows-specific library dependencies +#[cfg(target_os = "windows")] +extern crate dwrote; + +extern crate euclid; +extern crate fnv; + +#[cfg(target_os = "linux")] +extern crate fontconfig; +extern crate fontsan; +#[cfg(any(target_os = "linux", target_os = "android"))] +extern crate freetype; +extern crate gfx_traits; + +// Eventually we would like the shaper to be pluggable, as many operating systems have their own +// shapers. For now, however, this is a hard dependency. +extern crate harfbuzz_sys as harfbuzz; + +extern crate ipc_channel; #[macro_use] extern crate lazy_static; +#[cfg(any(target_os = "linux", target_os = "android"))] +extern crate libc; #[macro_use] extern crate log; +#[cfg_attr(target_os = "windows", macro_use)] +extern crate malloc_size_of; +extern crate net_traits; +extern crate ordered_float; +#[cfg(all( + feature = "unstable", + any(target_feature = "sse2", target_feature = "neon") +))] +extern crate packed_simd; +extern crate range; #[macro_use] extern crate serde; +#[cfg(any(target_os = "linux", target_os = "android"))] +extern crate servo_allocator; +extern crate servo_arc; #[macro_use] extern crate servo_atoms; +extern crate servo_url; +extern crate smallvec; +extern crate style; +extern crate time; +#[cfg(target_os = "windows")] +extern crate truetype; +extern crate ucd; +extern crate unicode_bidi; +extern crate unicode_script; +extern crate webrender_api; +extern crate xi_unicode; +#[cfg(target_os = "android")] +extern crate xml5ever; // Fonts #[macro_use] diff --git a/components/gfx/platform/freetype/android/font_list.rs b/components/gfx/platform/freetype/android/font_list.rs index d4b422ef111e..ebca244078e8 100644 --- a/components/gfx/platform/freetype/android/font_list.rs +++ b/components/gfx/platform/freetype/android/font_list.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::text::util::is_cjk; use std::cell::RefCell; use std::fs::File; use std::io::{self, Read}; use std::path::Path; +use text::util::is_cjk; use ucd::{Codepoint, UnicodeBlock}; +use xml5ever::Attribute; use xml5ever::driver::parse_document; use xml5ever::rcdom::*; use xml5ever::rcdom::{Node, RcDom}; use xml5ever::tendril::TendrilSink; -use xml5ever::Attribute; lazy_static! { static ref FONT_LIST: FontList = FontList::new(); @@ -127,11 +127,7 @@ struct FontList { impl FontList { fn new() -> FontList { // Possible paths containing the font mapping xml file. - let paths = [ - "/etc/fonts.xml", - "/system/etc/system_fonts.xml", - "/package/etc/fonts.xml", - ]; + let paths = ["/etc/fonts.xml", "/system/etc/system_fonts.xml"]; // Try to load and parse paths until one of them success. let mut result = None; @@ -140,10 +136,6 @@ impl FontList { !result.is_some() }); - if result.is_none() { - warn!("Couldn't find font list"); - } - match result { Some(result) => result, // If no xml mapping file is found fallback to some default @@ -217,10 +209,6 @@ impl FontList { let alternatives = [ ("sans-serif", "Roboto-Regular.ttf"), ("Droid Sans", "DroidSans.ttf"), - ( - "Lomino", - "/system/etc/ml/kali/Fonts/Lomino/Medium/LominoUI_Md.ttf", - ), ]; alternatives @@ -232,17 +220,12 @@ impl FontList { filename: item.1.into(), weight: None, }], - }) - .collect() + }).collect() } // All Android fonts are located in /system/fonts fn font_absolute_path(filename: &str) -> String { - if filename.starts_with("/") { - String::from(filename) - } else { - format!("/system/fonts/{}", filename) - } + format!("/system/fonts/{}", filename) } fn find_family(&self, name: &str) -> Option<&FontFamily> { @@ -356,8 +339,7 @@ impl FontList { .map(|f| Font { filename: f.clone(), weight: None, - }) - .collect(); + }).collect(); if !fonts.is_empty() { out.push(FontFamily { diff --git a/components/gfx/platform/freetype/font.rs b/components/gfx/platform/freetype/font.rs index ab315b7cc024..c774728fef02 100644 --- a/components/gfx/platform/freetype/font.rs +++ b/components/gfx/platform/freetype/font.rs @@ -2,15 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::c_str_to_string; use app_units::Au; -use crate::font::{FontHandleMethods, FontMetrics, FontTableMethods}; -use crate::font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; -use crate::platform::font_context::FontContextHandle; -use crate::platform::font_template::FontTemplateData; -use crate::text::glyph::GlyphId; -use crate::text::util::fixed_to_float; -use freetype::freetype::FT_Sfnt_Tag; +use font::{FontHandleMethods, FontMetrics, FontTableMethods}; +use font::{FontTableTag, FractionalPixel, GPOS, GSUB, KERN}; use freetype::freetype::{FT_Done_Face, FT_New_Face, FT_New_Memory_Face}; use freetype::freetype::{FT_F26Dot6, FT_Face, FT_FaceRec}; use freetype::freetype::{FT_Get_Char_Index, FT_Get_Postscript_Name}; @@ -19,16 +13,22 @@ use freetype::freetype::{FT_GlyphSlot, FT_Library, FT_Long, FT_ULong}; use freetype::freetype::{FT_Int32, FT_Kerning_Mode, FT_STYLE_FLAG_ITALIC}; use freetype::freetype::{FT_Load_Glyph, FT_Set_Char_Size}; use freetype::freetype::{FT_SizeRec, FT_Size_Metrics, FT_UInt, FT_Vector}; +use freetype::freetype::FT_Sfnt_Tag; use freetype::succeeded; use freetype::tt_os2::TT_OS2; +use platform::font_context::FontContextHandle; +use platform::font_template::FontTemplateData; use servo_atoms::Atom; +use std::{mem, ptr}; use std::ffi::CString; use std::os::raw::{c_char, c_long}; use std::sync::Arc; -use std::{mem, ptr}; use style::computed_values::font_stretch::T as FontStretch; use style::computed_values::font_weight::T as FontWeight; use style::values::computed::font::FontStyle; +use super::c_str_to_string; +use text::glyph::GlyphId; +use text::util::fixed_to_float; // This constant is not present in the freetype // bindings due to bindgen not handling the way @@ -216,8 +216,7 @@ impl FontHandleMethods for FontHandle { } } else { FontStretchKeyword::Normal - } - .compute(); + }.compute(); FontStretch(NonNegative(percentage)) } diff --git a/components/gfx/platform/freetype/font_context.rs b/components/gfx/platform/freetype/font_context.rs index 2da91cf5008d..dbc8816efc56 100644 --- a/components/gfx/platform/freetype/font_context.rs +++ b/components/gfx/platform/freetype/font_context.rs @@ -10,7 +10,7 @@ use freetype::freetype::FT_MemoryRec_; use freetype::freetype::FT_New_Library; use freetype::succeeded; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; -use servo_allocator::libc_compat::{free, malloc, realloc}; +use servo_allocator::libc_compat::{malloc, realloc, free}; use servo_allocator::usable_size; use std::os::raw::{c_long, c_void}; use std::ptr; diff --git a/components/gfx/platform/freetype/font_list.rs b/components/gfx/platform/freetype/font_list.rs index faebcc8703ba..e1ef486fa437 100644 --- a/components/gfx/platform/freetype/font_list.rs +++ b/components/gfx/platform/freetype/font_list.rs @@ -2,19 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use super::c_str_to_string; -use crate::text::util::is_cjk; use fontconfig::fontconfig::{FcChar8, FcResultMatch, FcSetSystem}; use fontconfig::fontconfig::{FcConfigGetCurrent, FcConfigGetFonts, FcConfigSubstitute}; use fontconfig::fontconfig::{FcDefaultSubstitute, FcFontMatch, FcNameParse, FcPatternGetString}; use fontconfig::fontconfig::{FcFontSetDestroy, FcMatchPattern, FcPatternCreate, FcPatternDestroy}; -use fontconfig::fontconfig::{ - FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString, -}; +use fontconfig::fontconfig::{FcFontSetList, FcObjectSetCreate, FcObjectSetDestroy, FcPatternAddString}; use fontconfig::fontconfig::{FcObjectSetAdd, FcPatternGetInteger}; +use libc; use libc::{c_char, c_int}; use std::ffi::CString; use std::ptr; +use super::c_str_to_string; +use text::util::is_cjk; static FC_FAMILY: &'static [u8] = b"family\0"; static FC_FILE: &'static [u8] = b"file\0"; diff --git a/components/gfx/platform/freetype/font_template.rs b/components/gfx/platform/freetype/font_template.rs index 90bb5677167c..674739b69cef 100644 --- a/components/gfx/platform/freetype/font_template.rs +++ b/components/gfx/platform/freetype/font_template.rs @@ -5,7 +5,7 @@ use servo_atoms::Atom; use std::fmt; use std::fs::File; -use std::io::{Error, Read}; +use std::io::{Read, Error}; use webrender_api::NativeFontHandle; /// Platform specific font representation for Linux. @@ -25,8 +25,7 @@ impl fmt::Debug for FontTemplateData { .field( "bytes", &self.bytes.as_ref().map(|b| format!("[{} bytes]", b.len())), - ) - .field("identifier", &self.identifier) + ).field("identifier", &self.identifier) .finish() } } diff --git a/components/gfx/platform/macos/font.rs b/components/gfx/platform/macos/font.rs index a27cc2a7c438..842c52fd70cc 100644 --- a/components/gfx/platform/macos/font.rs +++ b/components/gfx/platform/macos/font.rs @@ -11,20 +11,18 @@ use core_foundation::string::UniChar; use core_graphics::font::CGGlyph; use core_graphics::geometry::CGRect; use core_text::font::CTFont; -use core_text::font_descriptor::kCTFontDefaultOrientation; use core_text::font_descriptor::{SymbolicTraitAccessors, TraitAccessors}; -use crate::font::{ - FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel, -}; -use crate::font::{GPOS, GSUB, KERN}; -use crate::platform::font_template::FontTemplateData; -use crate::platform::macos::font_context::FontContextHandle; -use crate::text::glyph::GlyphId; +use core_text::font_descriptor::kCTFontDefaultOrientation; +use font::{FontHandleMethods, FontMetrics, FontTableMethods, FontTableTag, FractionalPixel}; +use font::{GPOS, GSUB, KERN}; +use platform::font_template::FontTemplateData; +use platform::macos::font_context::FontContextHandle; use servo_atoms::Atom; +use std::{fmt, ptr}; use std::ops::Range; use std::sync::Arc; -use std::{fmt, ptr}; use style::values::computed::font::{FontStretch, FontStyle, FontWeight}; +use text::glyph::GlyphId; const KERN_PAIR_LEN: usize = 6; @@ -237,10 +235,9 @@ impl FontHandleMethods for FontHandle { let mut glyphs: [CGGlyph; 1] = [0 as CGGlyph]; let count: CFIndex = 1; - let result = unsafe { - self.ctfont - .get_glyphs_for_characters(&characters[0], &mut glyphs[0], count) - }; + let result = self + .ctfont + .get_glyphs_for_characters(&characters[0], &mut glyphs[0], count); if !result { // No glyph for this character @@ -266,14 +263,12 @@ impl FontHandleMethods for FontHandle { fn glyph_h_advance(&self, glyph: GlyphId) -> Option { let glyphs = [glyph as CGGlyph]; - let advance = unsafe { - self.ctfont.get_advances_for_glyphs( - kCTFontDefaultOrientation, - &glyphs[0], - ptr::null_mut(), - 1, - ) - }; + let advance = self.ctfont.get_advances_for_glyphs( + kCTFontDefaultOrientation, + &glyphs[0], + ptr::null_mut(), + 1, + ); Some(advance as FractionalPixel) } diff --git a/components/gfx/platform/macos/font_list.rs b/components/gfx/platform/macos/font_list.rs index 845d48d825cf..df78a3917c83 100644 --- a/components/gfx/platform/macos/font_list.rs +++ b/components/gfx/platform/macos/font_list.rs @@ -2,7 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::text::util::unicode_plane; +use core_text; +use text::util::unicode_plane; use ucd::{Codepoint, UnicodeBlock}; pub fn for_each_available_family(mut callback: F) @@ -23,10 +24,9 @@ where let family_collection = core_text::font_collection::create_for_family(family_name); if let Some(family_collection) = family_collection { - if let Some(family_descriptors) = family_collection.get_descriptors() { - for family_descriptor in family_descriptors.iter() { - callback(family_descriptor.font_name()); - } + let family_descriptors = family_collection.get_descriptors(); + for family_descriptor in family_descriptors.iter() { + callback(family_descriptor.font_name()); } } } diff --git a/components/gfx/platform/macos/font_template.rs b/components/gfx/platform/macos/font_template.rs index fb8d5e1eda6c..85d134f45a2f 100644 --- a/components/gfx/platform/macos/font_template.rs +++ b/components/gfx/platform/macos/font_template.rs @@ -5,16 +5,17 @@ use app_units::Au; use core_graphics::data_provider::CGDataProvider; use core_graphics::font::CGFont; +use core_text; use core_text::font::CTFont; -use serde::de::{Error, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use serde::de::{Error, Visitor}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::HashMap; use std::fmt; use std::fs::File; -use std::io::{Error as IoError, Read}; +use std::io::{Read, Error as IoError}; use std::ops::Deref; use std::sync::{Arc, Mutex}; use webrender_api::NativeFontHandle; @@ -50,8 +51,7 @@ impl fmt::Debug for FontTemplateData { .font_data .as_ref() .map(|bytes| format!("[{} bytes]", bytes.len())), - ) - .finish() + ).finish() } } @@ -111,8 +111,7 @@ impl FontTemplateData { .expect("No URL for Core Text font!") .get_string() .to_string(), - ) - .expect("Couldn't parse Core Text font URL!") + ).expect("Couldn't parse Core Text font URL!") .as_url() .to_file_path() .expect("Core Text font didn't name a path!"); diff --git a/components/gfx/platform/mod.rs b/components/gfx/platform/mod.rs index a14abaafe477..106b232e3081 100644 --- a/components/gfx/platform/mod.rs +++ b/components/gfx/platform/mod.rs @@ -3,16 +3,16 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #[cfg(any(target_os = "linux", target_os = "android"))] -pub use crate::platform::freetype::{font, font_context}; +pub use platform::freetype::{font, font_context}; #[cfg(any(target_os = "linux", target_os = "android"))] -pub use crate::platform::freetype::{font_list, font_template}; +pub use platform::freetype::{font_list, font_template}; #[cfg(target_os = "windows")] -pub use crate::platform::windows::{font, font_context, font_list, font_template}; +pub use platform::windows::{font, font_context, font_list, font_template}; #[cfg(target_os = "macos")] -pub use crate::platform::macos::{font, font_context, font_list, font_template}; +pub use platform::macos::{font, font_context, font_list, font_template}; #[cfg(any(target_os = "linux", target_os = "android"))] mod freetype { diff --git a/components/gfx/platform/windows/font.rs b/components/gfx/platform/windows/font.rs index 30fce0c963dd..074bc62748a9 100644 --- a/components/gfx/platform/windows/font.rs +++ b/components/gfx/platform/windows/font.rs @@ -7,24 +7,24 @@ // renderer moves to a sandboxed process. use app_units::Au; -use crate::font::{FontHandleMethods, FontMetrics, FontTableMethods}; -use crate::font::{FontTableTag, FractionalPixel}; -use crate::platform::font_template::FontTemplateData; -use crate::platform::windows::font_context::FontContextHandle; -use crate::platform::windows::font_list::font_from_atom; -use crate::text::glyph::GlyphId; +use dwrote; use dwrote::{Font, FontFace, FontFile}; -use dwrote::{FontStretch, FontStyle}; +use dwrote::{FontWeight, FontStretch, FontStyle}; +use font::{FontHandleMethods, FontMetrics, FontTableMethods}; +use font::{FontTableTag, FractionalPixel}; +use platform::font_template::FontTemplateData; +use platform::windows::font_context::FontContextHandle; +use platform::windows::font_list::font_from_atom; use servo_atoms::Atom; -use std::fmt; -use std::ops::Deref; use std::sync::Arc; use style::computed_values::font_stretch::T as StyleFontStretch; use style::computed_values::font_weight::T as StyleFontWeight; use style::values::computed::font::FontStyle as StyleFontStyle; -use style::values::generics::font::FontStyle as GenericFontStyle; use style::values::generics::NonNegative; +use style::values::generics::font::FontStyle as GenericFontStyle; use style::values::specified::font::FontStretchKeyword; +use text::glyph::GlyphId; +use truetype; // 1em = 12pt = 16px, assuming 72 points per inch and 96 px per inch fn pt_to_px(pt: f64) -> f64 { @@ -117,7 +117,7 @@ struct FontInfo { impl FontInfo { fn new_from_face(face: &FontFace) -> Result { - use std::cmp::{max, min}; + use std::cmp::{min, max}; use std::io::Cursor; use truetype::{NamingTable, Value, WindowsMetrics}; @@ -185,8 +185,7 @@ impl FontInfo { 8 => FontStretchKeyword::ExtraExpanded, 9 => FontStretchKeyword::UltraExpanded, _ => return Err(()), - } - .compute(), + }.compute(), )); let style = if italic_bool { @@ -210,7 +209,21 @@ impl FontInfo { FontStyle::Oblique => GenericFontStyle::Oblique(StyleFontStyle::default_angle()), FontStyle::Italic => GenericFontStyle::Italic, }; - let weight = StyleFontWeight(font.weight().to_u32() as f32); + let weight = StyleFontWeight(match font.weight() { + FontWeight::Thin => 100., + FontWeight::ExtraLight => 200., + FontWeight::Light => 300., + // slightly grayer gray + FontWeight::SemiLight => 300., + FontWeight::Regular => 400., + FontWeight::Medium => 500., + FontWeight::SemiBold => 600., + FontWeight::Bold => 700., + FontWeight::ExtraBold => 800., + FontWeight::Black => 900., + // slightly blacker black + FontWeight::ExtraBlack => 1000., + }); let stretch = StyleFontStretch(NonNegative( match font.stretch() { FontStretch::Undefined => FontStretchKeyword::Normal, @@ -223,8 +236,7 @@ impl FontInfo { FontStretch::Expanded => FontStretchKeyword::Expanded, FontStretch::ExtraExpanded => FontStretchKeyword::ExtraExpanded, FontStretch::UltraExpanded => FontStretchKeyword::UltraExpanded, - } - .compute(), + }.compute(), )); Ok(FontInfo { @@ -240,7 +252,7 @@ impl FontInfo { #[derive(Debug)] pub struct FontHandle { font_data: Arc, - face: Nondebug, + face: FontFace, info: FontInfo, em_size: f32, du_per_em: f32, @@ -248,21 +260,6 @@ pub struct FontHandle { scaled_du_to_px: f32, } -struct Nondebug(T); - -impl fmt::Debug for Nondebug { - fn fmt(&self, _f: &mut fmt::Formatter) -> fmt::Result { - Ok(()) - } -} - -impl Deref for Nondebug { - type Target = T; - fn deref(&self) -> &T { - &self.0 - } -} - impl FontHandle {} impl FontHandleMethods for FontHandle { @@ -272,7 +269,7 @@ impl FontHandleMethods for FontHandle { pt_size: Option, ) -> Result { let (info, face) = if let Some(ref raw_font) = template.bytes { - let font_file = FontFile::new_from_data(Arc::new(raw_font.clone())); + let font_file = FontFile::new_from_data(&raw_font); if font_file.is_none() { // failed to load raw font return Err(()); @@ -301,7 +298,7 @@ impl FontHandleMethods for FontHandle { Ok(FontHandle { font_data: template.clone(), - face: Nondebug(face), + face: face, info: info, em_size: em_size, du_per_em: du_per_em, diff --git a/components/gfx/platform/windows/font_context.rs b/components/gfx/platform/windows/font_context.rs index 400988d032f2..7d304ed138db 100644 --- a/components/gfx/platform/windows/font_context.rs +++ b/components/gfx/platform/windows/font_context.rs @@ -2,8 +2,6 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use malloc_size_of::malloc_size_of_is_0; - #[derive(Clone, Debug)] pub struct FontContextHandle; diff --git a/components/gfx/platform/windows/font_list.rs b/components/gfx/platform/windows/font_list.rs index ac58f7c91d4d..b2d73b3db5ca 100644 --- a/components/gfx/platform/windows/font_list.rs +++ b/components/gfx/platform/windows/font_list.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::text::util::unicode_plane; -use dwrote::{Font, FontCollection, FontDescriptor}; +use dwrote::{Font, FontDescriptor, FontCollection}; use servo_atoms::Atom; use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; +use std::sync::atomic::{Ordering, AtomicUsize}; +use text::util::unicode_plane; use ucd::{Codepoint, UnicodeBlock}; lazy_static! { diff --git a/components/gfx/platform/windows/font_template.rs b/components/gfx/platform/windows/font_template.rs index 5a0cd14221d1..53eae0347fd5 100644 --- a/components/gfx/platform/windows/font_template.rs +++ b/components/gfx/platform/windows/font_template.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::platform::windows::font_list::{descriptor_from_atom, font_from_atom}; +use platform::windows::font_list::{descriptor_from_atom, font_from_atom}; use servo_atoms::Atom; use std::fmt; use std::io; @@ -24,8 +24,7 @@ impl fmt::Debug for FontTemplateData { .bytes .as_ref() .map(|bytes| format!("[{} bytes]", bytes.len())), - ) - .field("identifier", &self.identifier) + ).field("identifier", &self.identifier) .finish() } } diff --git a/components/gfx/tests/font_context.rs b/components/gfx/tests/font_context.rs index 14d4232243a2..8608f38329e1 100644 --- a/components/gfx/tests/font_context.rs +++ b/components/gfx/tests/font_context.rs @@ -2,11 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate app_units; +extern crate gfx; +extern crate servo_arc; +extern crate servo_atoms; +extern crate style; +extern crate webrender_api; + use app_units::Au; -use gfx::font::{ - fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope, -}; -use gfx::font_cache_thread::{FontTemplateInfo, FontTemplates}; +use gfx::font::{fallback_font_families, FontDescriptor, FontFamilyDescriptor, FontFamilyName, FontSearchScope}; +use gfx::font_cache_thread::{FontTemplates, FontTemplateInfo}; use gfx::font_context::{FontContext, FontContextHandle, FontSource}; use gfx::font_template::FontTemplateDescriptor; use servo_arc::Arc; @@ -19,9 +24,7 @@ use std::path::PathBuf; use std::rc::Rc; use style::properties::longhands::font_variant_caps::computed_value::T as FontVariantCaps; use style::properties::style_structs::Font as FontStyleStruct; -use style::values::computed::font::{ - FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize, -}; +use style::values::computed::font::{FamilyName, FamilyNameSyntax, FontFamily, FontFamilyList, FontSize}; use style::values::computed::font::{FontStretch, FontWeight, SingleFontFamily}; use style::values::generics::font::FontStyle; @@ -116,8 +119,7 @@ fn font_family(names: Vec<&str>) -> FontFamily { name: Atom::from(name), syntax: FamilyNameSyntax::Quoted, }) - }) - .collect(); + }).collect(); FontFamily(FontFamilyList::new(names.into_boxed_slice())) } diff --git a/components/gfx/tests/font_template.rs b/components/gfx/tests/font_template.rs index 132e067cf1a4..a6caea2f375d 100644 --- a/components/gfx/tests/font_template.rs +++ b/components/gfx/tests/font_template.rs @@ -2,6 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#[cfg(not(target_os = "macos"))] +extern crate gfx; +#[cfg(not(target_os = "macos"))] +extern crate servo_atoms; +#[cfg(not(target_os = "macos"))] +extern crate style; + // Test doesn't yet run on Mac, see https://github.com/servo/servo/pull/19928 for explanation. #[cfg(not(target_os = "macos"))] #[test] @@ -12,10 +19,10 @@ fn test_font_template_descriptor() { use std::fs::File; use std::io::prelude::*; use std::path::PathBuf; - use style::values::computed::font::{FontStretch, FontWeight}; use style::values::computed::Percentage; - use style::values::generics::font::FontStyle; + use style::values::computed::font::{FontStretch, FontWeight}; use style::values::generics::NonNegative; + use style::values::generics::font::FontStyle; fn descriptor(filename: &str) -> FontTemplateDescriptor { let mut path: PathBuf = [ @@ -34,8 +41,7 @@ fn test_font_template_descriptor() { let mut template = FontTemplate::new( Atom::from(filename), Some(file.bytes().map(|b| b.unwrap()).collect()), - ) - .unwrap(); + ).unwrap(); let context = FontContextHandle::new(); diff --git a/components/gfx/tests/text_util.rs b/components/gfx/tests/text_util.rs index 297823041d88..0b8132e9c885 100644 --- a/components/gfx/tests/text_util.rs +++ b/components/gfx/tests/text_util.rs @@ -2,7 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use gfx::text::util::{transform_text, CompressionMode}; +extern crate gfx; + +use gfx::text::util::{CompressionMode, transform_text}; #[test] fn test_transform_compress_none() { diff --git a/components/gfx/text/glyph.rs b/components/gfx/text/glyph.rs index d7029e862254..8e4c56e309b8 100644 --- a/components/gfx/text/glyph.rs +++ b/components/gfx/text/glyph.rs @@ -10,9 +10,9 @@ use euclid::Point2D; ))] use packed_simd::u32x4; use range::{self, EachIndex, Range, RangeIndex}; +use std::{fmt, mem, u16}; use std::cmp::{Ordering, PartialOrd}; use std::vec::Vec; -use std::{fmt, mem, u16}; pub use gfx_traits::ByteIndex; @@ -223,15 +223,16 @@ impl<'a> DetailedGlyphStore { entry_offset, glyphs ); - // TODO: don't actually assert this until asserts are compiled - // in/out based on severity, debug/release, etc. This assertion - // would wreck the complexity of the lookup. - // - // See Rust Issue #3647, #2228, #3627 for related information. - // - // do self.detail_lookup.borrow |arr| { - // assert !arr.contains(entry) - // } + /* TODO: don't actually assert this until asserts are compiled + in/out based on severity, debug/release, etc. This assertion + would wreck the complexity of the lookup. + + See Rust Issue #3647, #2228, #3627 for related information. + + do self.detail_lookup.borrow |arr| { + assert !arr.contains(entry) + } + */ self.detail_lookup.push(entry); self.detail_buffer.extend_from_slice(glyphs); @@ -540,8 +541,7 @@ impl<'a> GlyphStore { data_for_glyphs[i].advance, data_for_glyphs[i].offset, ) - }) - .collect(); + }).collect(); self.has_detailed_glyphs = true; self.detail_store diff --git a/components/gfx/text/mod.rs b/components/gfx/text/mod.rs index c65359ae1ddb..24c434e2e699 100644 --- a/components/gfx/text/mod.rs +++ b/components/gfx/text/mod.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -pub use crate::text::shaping::Shaper; -pub use crate::text::text_run::TextRun; +pub use text::shaping::Shaper; +pub use text::text_run::TextRun; pub mod glyph; pub mod shaping; diff --git a/components/gfx/text/shaping/harfbuzz.rs b/components/gfx/text/shaping/harfbuzz.rs index ecd575d9b91f..eb6b7b8cd4aa 100644 --- a/components/gfx/text/shaping/harfbuzz.rs +++ b/components/gfx/text/shaping/harfbuzz.rs @@ -5,42 +5,40 @@ #![allow(unsafe_code)] use app_units::Au; -use crate::font::{Font, FontTableMethods, FontTableTag, ShapingFlags, ShapingOptions, KERN}; -use crate::platform::font::FontTable; -use crate::text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; -use crate::text::shaping::ShaperMethods; -use crate::text::util::{fixed_to_float, float_to_fixed, is_bidi_control}; use euclid::Point2D; -// Eventually we would like the shaper to be pluggable, as many operating systems have their own -// shapers. For now, however, HarfBuzz is a hard dependency. -use harfbuzz_sys::hb_blob_t; -use harfbuzz_sys::hb_bool_t; -use harfbuzz_sys::hb_buffer_add_utf8; -use harfbuzz_sys::hb_buffer_destroy; -use harfbuzz_sys::hb_buffer_get_glyph_positions; -use harfbuzz_sys::hb_buffer_get_length; -use harfbuzz_sys::hb_face_destroy; -use harfbuzz_sys::hb_feature_t; -use harfbuzz_sys::hb_font_create; -use harfbuzz_sys::hb_font_funcs_create; -use harfbuzz_sys::hb_font_funcs_set_glyph_h_advance_func; -use harfbuzz_sys::hb_font_funcs_set_glyph_h_kerning_func; -use harfbuzz_sys::hb_font_funcs_set_nominal_glyph_func; -use harfbuzz_sys::hb_font_set_funcs; -use harfbuzz_sys::hb_font_set_ppem; -use harfbuzz_sys::hb_font_set_scale; -use harfbuzz_sys::hb_glyph_info_t; -use harfbuzz_sys::hb_glyph_position_t; -use harfbuzz_sys::{hb_blob_create, hb_face_create_for_tables}; -use harfbuzz_sys::{hb_buffer_create, hb_font_destroy}; -use harfbuzz_sys::{hb_buffer_get_glyph_infos, hb_shape}; -use harfbuzz_sys::{hb_buffer_set_direction, hb_buffer_set_script}; -use harfbuzz_sys::{hb_buffer_t, hb_codepoint_t, hb_font_funcs_t}; -use harfbuzz_sys::{hb_face_t, hb_font_t}; -use harfbuzz_sys::{hb_position_t, hb_tag_t}; -use harfbuzz_sys::{HB_DIRECTION_LTR, HB_DIRECTION_RTL, HB_MEMORY_MODE_READONLY}; -use std::os::raw::{c_char, c_int, c_uint, c_void}; +use font::{ShapingFlags, Font, FontTableMethods, FontTableTag, ShapingOptions, KERN}; +use harfbuzz::{HB_DIRECTION_LTR, HB_DIRECTION_RTL, HB_MEMORY_MODE_READONLY}; +use harfbuzz::{hb_blob_create, hb_face_create_for_tables}; +use harfbuzz::{hb_buffer_create, hb_font_destroy}; +use harfbuzz::{hb_buffer_get_glyph_infos, hb_shape}; +use harfbuzz::{hb_buffer_set_direction, hb_buffer_set_script}; +use harfbuzz::{hb_buffer_t, hb_codepoint_t, hb_font_funcs_t}; +use harfbuzz::{hb_face_t, hb_font_t}; +use harfbuzz::{hb_position_t, hb_tag_t}; +use harfbuzz::hb_blob_t; +use harfbuzz::hb_bool_t; +use harfbuzz::hb_buffer_add_utf8; +use harfbuzz::hb_buffer_destroy; +use harfbuzz::hb_buffer_get_glyph_positions; +use harfbuzz::hb_buffer_get_length; +use harfbuzz::hb_face_destroy; +use harfbuzz::hb_feature_t; +use harfbuzz::hb_font_create; +use harfbuzz::hb_font_funcs_create; +use harfbuzz::hb_font_funcs_set_glyph_h_advance_func; +use harfbuzz::hb_font_funcs_set_glyph_h_kerning_func; +use harfbuzz::hb_font_funcs_set_nominal_glyph_func; +use harfbuzz::hb_font_set_funcs; +use harfbuzz::hb_font_set_ppem; +use harfbuzz::hb_font_set_scale; +use harfbuzz::hb_glyph_info_t; +use harfbuzz::hb_glyph_position_t; +use platform::font::FontTable; use std::{char, cmp, ptr}; +use std::os::raw::{c_char, c_int, c_uint, c_void}; +use text::glyph::{ByteIndex, GlyphData, GlyphId, GlyphStore}; +use text::shaping::ShaperMethods; +use text::util::{fixed_to_float, float_to_fixed, is_bidi_control}; const NO_GLYPH: i32 = -1; const LIGA: u32 = ot_tag!('l', 'i', 'g', 'a'); diff --git a/components/gfx/text/shaping/mod.rs b/components/gfx/text/shaping/mod.rs index 9f78c0d75ac3..97d969805967 100644 --- a/components/gfx/text/shaping/mod.rs +++ b/components/gfx/text/shaping/mod.rs @@ -7,10 +7,10 @@ //! //! Currently, only harfbuzz bindings are implemented. -use crate::font::ShapingOptions; -use crate::text::glyph::GlyphStore; +use font::ShapingOptions; +use text::glyph::GlyphStore; -pub use self::harfbuzz::Shaper; +pub use text::shaping::harfbuzz::Shaper; pub mod harfbuzz; diff --git a/components/gfx/text/text_run.rs b/components/gfx/text/text_run.rs index 591832de459f..39b96a934e65 100644 --- a/components/gfx/text/text_run.rs +++ b/components/gfx/text/text_run.rs @@ -3,17 +3,18 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::Au; -use crate::font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; -use crate::font::{RunMetrics, ShapingOptions}; -use crate::platform::font_template::FontTemplateData; -use crate::text::glyph::{ByteIndex, GlyphStore}; +use font::{Font, FontHandleMethods, FontMetrics, ShapingFlags}; +use font::{RunMetrics, ShapingOptions}; +use platform::font_template::FontTemplateData; use range::Range; use std::cell::Cell; -use std::cmp::{max, Ordering}; +use std::cmp::{Ordering, max}; use std::slice::Iter; use std::sync::Arc; use style::str::char_is_whitespace; +use text::glyph::{ByteIndex, GlyphStore}; use unicode_bidi as bidi; +use webrender_api; use xi_unicode::LineBreakLeafIter; thread_local! { @@ -22,7 +23,7 @@ thread_local! { } /// A single "paragraph" of text in one font size and style. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct TextRun { /// The UTF-8 string represented by this text run. pub text: Arc, @@ -50,7 +51,7 @@ impl Drop for TextRun { } /// A single series of glyphs within a text run. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct GlyphRun { /// The glyphs. pub glyph_store: Arc, @@ -379,8 +380,7 @@ impl<'a> TextRun { ); remaining -= slice_advance; slice_index - }) - .sum() + }).sum() } /// Returns an iterator that will iterate over all slices of glyphs that represent natural diff --git a/components/gfx_traits/Cargo.toml b/components/gfx_traits/Cargo.toml index c52dbc18912f..8d558d19ba0b 100644 --- a/components/gfx_traits/Cargo.toml +++ b/components/gfx_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "gfx_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/gfx_traits/lib.rs b/components/gfx_traits/lib.rs index f540ed61be63..457814abddfb 100644 --- a/components/gfx_traits/lib.rs +++ b/components/gfx_traits/lib.rs @@ -6,6 +6,7 @@ #![crate_type = "rlib"] #![deny(unsafe_code)] +extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[macro_use] @@ -16,7 +17,7 @@ extern crate serde; pub mod print_tree; use range::RangeIndex; -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; /// A newtype struct for denoting the age of messages; prevents race conditions. #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)] diff --git a/components/hashglobe/src/fake.rs b/components/hashglobe/src/fake.rs index d2cdd549e48d..c5cd9d39bb75 100644 --- a/components/hashglobe/src/fake.rs +++ b/components/hashglobe/src/fake.rs @@ -20,8 +20,8 @@ use std::fmt; use std::hash::{BuildHasher, Hash}; use std::ops::{Deref, DerefMut}; -pub use std::collections::hash_map::{Entry, Iter as MapIter, IterMut as MapIterMut, RandomState}; -pub use std::collections::hash_set::{IntoIter as SetIntoIter, Iter as SetIter}; +pub use std::collections::hash_map::{Entry, RandomState, Iter as MapIter, IterMut as MapIterMut}; +pub use std::collections::hash_set::{Iter as SetIter, IntoIter as SetIntoIter}; #[derive(Clone)] pub struct HashMap(StdMap); diff --git a/components/hashglobe/src/hash_map.rs b/components/hashglobe/src/hash_map.rs index 03ade951e1ec..57ac9bcc049c 100644 --- a/components/hashglobe/src/hash_map.rs +++ b/components/hashglobe/src/hash_map.rs @@ -15,13 +15,13 @@ use std::borrow::Borrow; use std::cmp::max; use std::fmt::{self, Debug}; #[allow(deprecated)] -use std::hash::{BuildHasher, Hash}; +use std::hash::{Hash, BuildHasher}; use std::iter::FromIterator; use std::mem::{self, replace}; use std::ops::{Deref, Index}; -use super::table::BucketState::{Empty, Full}; use super::table::{self, Bucket, EmptyBucket, FullBucket, FullBucketMut, RawTable, SafeHash}; +use super::table::BucketState::{Empty, Full}; use FailedAllocationError; @@ -2214,11 +2214,11 @@ fn assert_covariance() { #[cfg(test)] mod test_map { extern crate rand; - use self::rand::{thread_rng, Rng}; - use super::Entry::{Occupied, Vacant}; use super::HashMap; + use super::Entry::{Occupied, Vacant}; use super::RandomState; use cell::RefCell; + use self::rand::{thread_rng, Rng}; #[test] fn test_zero_capacities() { diff --git a/components/hashglobe/src/hash_set.rs b/components/hashglobe/src/hash_set.rs index 694e01c46eb8..34e657e44fcc 100644 --- a/components/hashglobe/src/hash_set.rs +++ b/components/hashglobe/src/hash_set.rs @@ -10,12 +10,12 @@ use std::borrow::Borrow; use std::fmt; -use std::hash::{BuildHasher, Hash}; +use std::hash::{Hash, BuildHasher}; use std::iter::{Chain, FromIterator}; -use std::ops::{BitAnd, BitOr, BitXor, Sub}; +use std::ops::{BitOr, BitAnd, BitXor, Sub}; -use super::hash_map::{self, HashMap, Keys, RandomState}; use super::Recover; +use super::hash_map::{self, HashMap, Keys, RandomState}; // Future Optimization (FIXME!) // ============================= @@ -1258,8 +1258,8 @@ fn assert_covariance() { #[cfg(test)] mod test_set { - use super::hash_map::RandomState; use super::HashSet; + use super::hash_map::RandomState; #[test] fn test_zero_capacities() { diff --git a/components/hashglobe/src/table.rs b/components/hashglobe/src/table.rs index 15e3394884ff..0b8b49001e2d 100644 --- a/components/hashglobe/src/table.rs +++ b/components/hashglobe/src/table.rs @@ -9,13 +9,13 @@ // except according to those terms. use alloc::{alloc, dealloc}; -use shim::{Shared, Unique}; use std::cmp; use std::hash::{BuildHasher, Hash, Hasher}; use std::marker; use std::mem::{self, align_of, size_of}; use std::ops::{Deref, DerefMut}; use std::ptr; +use shim::{Unique, Shared}; use self::BucketState::*; use FailedAllocationError; diff --git a/components/jstraceable_derive/Cargo.toml b/components/jstraceable_derive/Cargo.toml index ecd035d1c093..0b85fac1045f 100644 --- a/components/jstraceable_derive/Cargo.toml +++ b/components/jstraceable_derive/Cargo.toml @@ -3,7 +3,6 @@ name = "jstraceable_derive" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/jstraceable_derive/lib.rs b/components/jstraceable_derive/lib.rs index 8bac2c39defc..ac793f4d85ae 100644 --- a/components/jstraceable_derive/lib.rs +++ b/components/jstraceable_derive/lib.rs @@ -2,6 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate quote; #[macro_use] extern crate syn; #[macro_use] @@ -20,16 +21,16 @@ fn js_traceable_derive(s: synstructure::Structure) -> quote::Tokens { let ident = param.ident; where_clause .predicates - .push(parse_quote!(#ident: crate::dom::bindings::trace::JSTraceable)) + .push(parse_quote!(#ident: ::dom::bindings::trace::JSTraceable)) } let tokens = quote! { #[allow(unsafe_code)] - unsafe impl #impl_generics crate::dom::bindings::trace::JSTraceable for #name #ty_generics #where_clause { + unsafe impl #impl_generics ::dom::bindings::trace::JSTraceable for #name #ty_generics #where_clause { #[inline] #[allow(unused_variables, unused_imports)] - unsafe fn trace(&self, tracer: *mut js::jsapi::JSTracer) { - use crate::dom::bindings::trace::JSTraceable; + unsafe fn trace(&self, tracer: *mut ::js::jsapi::JSTracer) { + use ::dom::bindings::trace::JSTraceable; match *self { #match_body } diff --git a/components/layout/Cargo.toml b/components/layout/Cargo.toml index 9a960b513056..82dfc9920043 100644 --- a/components/layout/Cargo.toml +++ b/components/layout/Cargo.toml @@ -3,7 +3,6 @@ name = "layout" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/layout/animation.rs b/components/layout/animation.rs index 0903c1b7fa5b..b42933bb4003 100644 --- a/components/layout/animation.rs +++ b/components/layout/animation.rs @@ -4,17 +4,17 @@ //! CSS transitions and animations. -use crate::context::LayoutContext; -use crate::display_list::items::OpaqueNode; -use crate::flow::{Flow, GetBaseFlow}; -use crate::opaque_node::OpaqueNodeMethods; +use context::LayoutContext; +use display_list::items::OpaqueNode; +use flow::{Flow, GetBaseFlow}; use fxhash::FxHashMap; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use script_traits::UntrustedNodeAddress; +use opaque_node::OpaqueNodeMethods; use script_traits::{AnimationState, ConstellationControlMsg, LayoutMsg as ConstellationMsg}; +use script_traits::UntrustedNodeAddress; use servo_channel::Receiver; -use style::animation::{update_style_for_animation, Animation}; +use style::animation::{Animation, update_style_for_animation}; use style::dom::TElement; use style::font_metrics::ServoMetricsProvider; use style::selector_parser::RestyleDamage; @@ -79,7 +79,7 @@ pub fn update_animation_state( let mut animations_still_running = vec![]; for mut running_animation in running_animations.drain(..) { let still_running = !running_animation.is_expired() && match running_animation { - Animation::Transition(_, started_at, ref frame) => { + Animation::Transition(_, started_at, ref frame, _expired) => { now < started_at + frame.duration }, Animation::Keyframes(_, _, _, ref mut state) => { @@ -89,24 +89,18 @@ pub fn update_animation_state( }, }; - debug!( - "update_animation_state({:?}): {:?}", - still_running, running_animation - ); - if still_running { animations_still_running.push(running_animation); continue; } - if let Animation::Transition(node, _, ref frame) = running_animation { + if let Animation::Transition(node, _, ref frame, _) = running_animation { script_chan .send(ConstellationControlMsg::TransitionEnd( node.to_untrusted_node_address(), frame.property_animation.property_name().into(), frame.duration, - )) - .unwrap(); + )).unwrap(); } expired_animations @@ -155,15 +149,14 @@ pub fn update_animation_state( .send(ConstellationMsg::ChangeRunningAnimationsState( pipeline_id, animation_state, - )) - .unwrap(); + )).unwrap(); } /// Recalculates style for a set of animations. This does *not* run with the DOM /// lock held. pub fn recalc_style_for_animations( context: &LayoutContext, - flow: &mut dyn Flow, + flow: &mut Flow, animations: &FxHashMap>, ) where E: TElement, diff --git a/components/layout/block.rs b/components/layout/block.rs index 429662d29b5a..ae1bc242e329 100644 --- a/components/layout/block.rs +++ b/components/layout/block.rs @@ -25,32 +25,25 @@ //! //! http://dev.w3.org/csswg/css-sizing/ +#![deny(unsafe_code)] + use app_units::{Au, MAX_AU}; -use crate::context::LayoutContext; -use crate::display_list::items::DisplayListSection; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionFlags}; -use crate::floats::{ClearType, FloatKind, Floats, PlacementInfo}; -use crate::flow::{ - BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ForceNonfloatedFlag, GetBaseFlow, -}; -use crate::flow::{ - FlowFlags, FragmentationContext, ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow, -}; -use crate::flow_list::FlowList; -use crate::fragment::{ - CoordinateSystem, Fragment, FragmentBorderBoxIterator, FragmentFlags, Overflow, -}; -use crate::incremental::RelayoutMode; -use crate::layout_debug; -use crate::model::{ - AdjoiningMargins, CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo, MaybeAuto, -}; -use crate::sequential; -use crate::traversal::PreorderFlowTraversal; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; +use display_list::{DisplayListBuildState, StackingContextCollectionFlags}; +use display_list::StackingContextCollectionState; +use display_list::items::DisplayListSection; use euclid::{Point2D, Rect, SideOffsets2D, Size2D}; +use floats::{ClearType, FloatKind, Floats, PlacementInfo}; +use flow::{BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ForceNonfloatedFlag, GetBaseFlow}; +use flow::{ImmutableFlowUtils, LateAbsolutePositionInfo, OpaqueFlow, FragmentationContext, FlowFlags}; +use flow_list::FlowList; +use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow, FragmentFlags}; use gfx_traits::print_tree::PrintTree; +use incremental::RelayoutMode; +use layout_debug; +use model::{AdjoiningMargins, CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo, MaybeAuto}; +use sequential; use serde::{Serialize, Serializer}; use servo_geometry::MaxRect; use std::cmp::{max, min}; @@ -66,8 +59,9 @@ use style::context::SharedStyleContext; use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect, LogicalSize, WritingMode}; use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; +use style::values::computed::{LengthOrPercentageOrNone, LengthOrPercentage}; use style::values::computed::LengthOrPercentageOrAuto; -use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrNone}; +use traversal::PreorderFlowTraversal; /// Information specific to floated blocks. #[derive(Clone, Serialize)] @@ -546,7 +540,7 @@ pub struct AbsoluteAssignBSizesTraversal<'a>(pub &'a SharedStyleContext<'a>); impl<'a> PreorderFlowTraversal for AbsoluteAssignBSizesTraversal<'a> { #[inline] - fn process(&self, flow: &mut dyn Flow) { + fn process(&self, flow: &mut Flow) { if !flow.is_block_like() { return; } @@ -599,7 +593,7 @@ pub enum FormattingContextType { } #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for BlockFlow {} +unsafe impl ::flow::HasBaseFlow for BlockFlow {} // A block formatting context. #[derive(Serialize)] @@ -938,7 +932,7 @@ impl BlockFlow { layout_context: &LayoutContext, mut fragmentation_context: Option, margins_may_collapse: MarginsMayCollapseFlag, - ) -> Option> { + ) -> Option> { let _scope = layout_debug_scope!("assign_block_size_block_base {:x}", self.base.debug_id()); let mut break_at = None; @@ -1272,7 +1266,7 @@ impl BlockFlow { } } - if (&*self as &dyn Flow).contains_roots_of_absolute_flow_tree() { + if (&*self as &Flow).contains_roots_of_absolute_flow_tree() { // Assign block-sizes for all flows in this absolute flow tree. // This is preorder because the block-size of an absolute flow may depend on // the block-size of its containing block, which may also be an absolute flow. @@ -1307,7 +1301,7 @@ impl BlockFlow { if let Some(child) = child_remaining { children.push_front_arc(child); } - Some(Arc::new(self.clone_with_children(children)) as Arc) + Some(Arc::new(self.clone_with_children(children)) as Arc) } }) } @@ -1342,8 +1336,7 @@ impl BlockFlow { self.fragment.style.writing_mode, inline_size_for_float_placement, block_size + self.fragment.margin.block_start_end(), - ) - .convert( + ).convert( self.fragment.style.writing_mode, self.base.floats.writing_mode, ), @@ -1370,8 +1363,7 @@ impl BlockFlow { self.base.floats.writing_mode, self.base.writing_mode, container_size, - ) - .start; + ).start; let margin_offset = LogicalPoint::new( self.base.writing_mode, Au(0), @@ -1592,7 +1584,7 @@ impl BlockFlow { content_inline_size: Au, mut callback: F, ) where - F: FnMut(&mut dyn Flow, usize, Au, WritingMode, &mut Au, &mut Au), + F: FnMut(&mut Flow, usize, Au, WritingMode, &mut Au, &mut Au), { let flags = self.base.flags.clone(); @@ -2246,7 +2238,7 @@ impl Flow for BlockFlow { self.assign_inline_position_for_formatting_context(layout_context, content_box); } - if (self as &dyn Flow).floats_might_flow_through() { + if (self as &Flow).floats_might_flow_through() { self.base.thread_id = parent_thread_id; if self .base @@ -2283,7 +2275,7 @@ impl Flow for BlockFlow { &mut self, layout_context: &LayoutContext, fragmentation_context: Option, - ) -> Option> { + ) -> Option> { if self.fragment.is_replaced() { let _scope = layout_debug_scope!( "assign_replaced_block_size_if_necessary {:x}", @@ -2595,7 +2587,7 @@ impl Flow for BlockFlow { self.build_display_list_for_block(state, BorderPaintingMode::Separate); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.fragment.repair_style(new_style) } @@ -2613,7 +2605,7 @@ impl Flow for BlockFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -2636,12 +2628,11 @@ impl Flow for BlockFlow { .early_absolute_position_info .relative_containing_block_mode, CoordinateSystem::Own, - ) - .translate(&stacking_context_position.to_vector()), + ).translate(&stacking_context_position.to_vector()), ); } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { (*mutator)(&mut self.fragment) } diff --git a/components/layout/construct.rs b/components/layout/construct.rs index ee0e0ee451ab..36ab116d0cac 100644 --- a/components/layout/construct.rs +++ b/components/layout/construct.rs @@ -11,54 +11,37 @@ //! maybe it's an absolute or fixed position thing that hasn't found its containing block yet. //! Construction items bubble up the tree from children to parents until they find their homes. -use crate::block::BlockFlow; -use crate::context::{with_thread_local_font_context, LayoutContext}; -use crate::data::{LayoutData, LayoutDataFlags}; -use crate::display_list::items::OpaqueNode; -use crate::flex::FlexFlow; -use crate::floats::FloatKind; -use crate::flow::{AbsoluteDescendants, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils}; -use crate::flow::{FlowFlags, MutableFlowUtils, MutableOwnedFlowUtils}; -use crate::flow_ref::FlowRef; -use crate::fragment::{ - CanvasFragmentInfo, Fragment, FragmentFlags, GeneratedContentInfo, IframeFragmentInfo, -}; -use crate::fragment::{ - ImageFragmentInfo, InlineAbsoluteFragmentInfo, InlineAbsoluteHypotheticalFragmentInfo, -}; -use crate::fragment::{ - InlineBlockFragmentInfo, MediaFragmentInfo, SpecificFragmentInfo, SvgFragmentInfo, -}; -use crate::fragment::{ - TableColumnFragmentInfo, UnscannedTextFragmentInfo, WhitespaceStrippingResult, -}; -use crate::inline::{InlineFlow, InlineFragmentNodeFlags, InlineFragmentNodeInfo}; -use crate::linked_list::prepend_from; -use crate::list_item::{ListItemFlow, ListStyleTypeContent}; -use crate::multicol::{MulticolColumnFlow, MulticolFlow}; -use crate::parallel; -use crate::table::TableFlow; -use crate::table_caption::TableCaptionFlow; -use crate::table_cell::TableCellFlow; -use crate::table_colgroup::TableColGroupFlow; -use crate::table_row::TableRowFlow; -use crate::table_rowgroup::TableRowGroupFlow; -use crate::table_wrapper::TableWrapperFlow; -use crate::text::TextRunScanner; -use crate::traversal::PostorderNodeMutTraversal; -use crate::wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers}; -use crate::ServoArc; -use script_layout_interface::wrapper_traits::{ - PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, -}; -use script_layout_interface::{is_image_data, LayoutElementType, LayoutNodeType}; +#![deny(unsafe_code)] + +use ServoArc; +use block::BlockFlow; +use context::{LayoutContext, with_thread_local_font_context}; +use data::{LayoutDataFlags, LayoutData}; +use display_list::items::OpaqueNode; +use flex::FlexFlow; +use floats::FloatKind; +use flow::{AbsoluteDescendants, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils}; +use flow::{FlowFlags, MutableFlowUtils, MutableOwnedFlowUtils}; +use flow_ref::FlowRef; +use fragment::{CanvasFragmentInfo, ImageFragmentInfo, InlineAbsoluteFragmentInfo, SvgFragmentInfo}; +use fragment::{Fragment, GeneratedContentInfo, IframeFragmentInfo, FragmentFlags}; +use fragment::{InlineAbsoluteHypotheticalFragmentInfo, TableColumnFragmentInfo}; +use fragment::{InlineBlockFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; +use fragment::WhitespaceStrippingResult; +use inline::{InlineFlow, InlineFragmentNodeInfo, InlineFragmentNodeFlags}; +use linked_list::prepend_from; +use list_item::{ListItemFlow, ListStyleTypeContent}; +use multicol::{MulticolColumnFlow, MulticolFlow}; +use parallel; +use script_layout_interface::{LayoutElementType, LayoutNodeType, is_image_data}; +use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use servo_config::opts; use servo_url::ServoUrl; use std::collections::LinkedList; use std::marker::PhantomData; use std::mem; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use style::computed_values::caption_side::T as CaptionSide; use style::computed_values::display::T as Display; use style::computed_values::empty_cells::T as EmptyCells; @@ -73,6 +56,16 @@ use style::selector_parser::{PseudoElement, RestyleDamage}; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::generics::counters::ContentItem; use style::values::generics::url::UrlOrNone as ImageUrlOrNone; +use table::TableFlow; +use table_caption::TableCaptionFlow; +use table_cell::TableCellFlow; +use table_colgroup::TableColGroupFlow; +use table_row::TableRowFlow; +use table_rowgroup::TableRowGroupFlow; +use table_wrapper::TableWrapperFlow; +use text::TextRunScanner; +use traversal::PostorderNodeMutTraversal; +use wrapper::{LayoutNodeLayoutData, TextContent, ThreadSafeLayoutNodeHelpers}; /// The results of flow construction for a DOM node. #[derive(Clone)] @@ -195,8 +188,7 @@ impl InlineBlockSplit { predecessors: mem::replace( fragment_accumulator, InlineFragmentsAccumulator::from_inline_node(node, style_context), - ) - .to_intermediate_inline_fragments::(style_context), + ).to_intermediate_inline_fragments::(style_context), flow: flow, }; @@ -414,10 +406,6 @@ impl<'a, ConcreteThreadSafeLayoutNode: ThreadSafeLayoutNode> )); SpecificFragmentInfo::Image(image_info) }, - Some(LayoutNodeType::Element(LayoutElementType::HTMLMediaElement)) => { - let data = node.media_data().unwrap(); - SpecificFragmentInfo::Media(Box::new(MediaFragmentInfo::new(data))) - }, Some(LayoutNodeType::Element(LayoutElementType::HTMLObjectElement)) => { let image_info = Box::new(ImageFragmentInfo::new( node.object_data(), @@ -1968,7 +1956,6 @@ where match self.type_id() { Some(LayoutNodeType::Text) | Some(LayoutNodeType::Element(LayoutElementType::HTMLImageElement)) | - Some(LayoutNodeType::Element(LayoutElementType::HTMLMediaElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLIFrameElement)) | Some(LayoutNodeType::Element(LayoutElementType::HTMLCanvasElement)) | Some(LayoutNodeType::Element(LayoutElementType::SVGSVGElement)) => true, diff --git a/components/layout/context.rs b/components/layout/context.rs index 08530e74a5c3..a87173d633e8 100644 --- a/components/layout/context.rs +++ b/components/layout/context.rs @@ -4,8 +4,7 @@ //! Data needed by the layout thread. -use crate::display_list::items::{OpaqueNode, WebRenderImageInfo}; -use crate::opaque_node::OpaqueNodeMethods; +use display_list::items::{WebRenderImageInfo, OpaqueNode}; use fnv::FnvHasher; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context::FontContext; @@ -13,6 +12,7 @@ use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use msg::constellation_msg::PipelineId; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageState}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; +use opaque_node::OpaqueNodeMethods; use parking_lot::RwLock; use script_layout_interface::{PendingImage, PendingImageState}; use script_traits::Painter; @@ -64,7 +64,7 @@ pub struct LayoutContext<'a> { pub style_context: SharedStyleContext<'a>, /// Reference to the script thread image cache. - pub image_cache: Arc, + pub image_cache: Arc, /// Interface to the font cache thread. pub font_cache_thread: Mutex, @@ -77,7 +77,7 @@ pub struct LayoutContext<'a> { >, /// Paint worklets - pub registered_painters: &'a dyn RegisteredPainters, + pub registered_painters: &'a RegisteredPainters, /// A list of in-progress image loads to be shared with the script thread. /// A None value means that this layout was not initiated by the script thread. @@ -197,5 +197,5 @@ pub trait RegisteredPainter: RegisteredSpeculativePainter + Painter {} /// A set of registered painters pub trait RegisteredPainters: Sync { /// Look up a painter - fn get(&self, name: &Atom) -> Option<&dyn RegisteredPainter>; + fn get(&self, name: &Atom) -> Option<&RegisteredPainter>; } diff --git a/components/layout/data.rs b/components/layout/data.rs index dab6aec56171..2df8ea6432be 100644 --- a/components/layout/data.rs +++ b/components/layout/data.rs @@ -3,7 +3,7 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use atomic_refcell::AtomicRefCell; -use crate::construct::ConstructionResult; +use construct::ConstructionResult; use script_layout_interface::StyleData; #[repr(C)] diff --git a/components/layout/display_list/background.rs b/components/layout/display_list/background.rs index a8d0cebde12c..6e4751f3012b 100644 --- a/components/layout/display_list/background.rs +++ b/components/layout/display_list/background.rs @@ -2,21 +2,50 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -// FIXME(rust-lang/rust#26264): Remove GenericBackgroundSize. +//! Calculations for CSS images, backgrounds and borders. +//! +//! * [CSS Images Module Level 3](https://drafts.csswg.org/css-images-3/) +//! * [CSS Backgrounds and Borders Module Level 3](https://drafts.csswg.org/css-backgrounds-3/) + +#![deny(unsafe_code)] + +// FIXME(rust-lang/rust#26264): Remove GenericEndingShape and GenericGradientItem. use app_units::Au; -use crate::display_list::border; -use crate::model::MaybeAuto; -use euclid::{Point2D, Rect, SideOffsets2D, Size2D}; +use display_list::ToLayout; +use display_list::items::WebRenderImageInfo; +use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Vector2D}; +use model::{self, MaybeAuto}; use style::computed_values::background_attachment::single_value::T as BackgroundAttachment; use style::computed_values::background_clip::single_value::T as BackgroundClip; use style::computed_values::background_origin::single_value::T as BackgroundOrigin; -use style::properties::style_structs::Background; -use style::values::computed::{BackgroundSize, LengthOrPercentageOrAuto}; -use style::values::generics::background::BackgroundSize as GenericBackgroundSize; +use style::computed_values::border_image_outset::T as BorderImageOutset; +use style::properties::ComputedValues; +use style::properties::style_structs::{self, Background}; +use style::values::Either; +use style::values::computed::{Angle, GradientItem, BackgroundSize as ComputedBackgroundSize}; +use style::values::computed::{LengthOrNumber, LengthOrPercentage, LengthOrPercentageOrAuto}; +use style::values::computed::{NumberOrPercentage, Percentage, Position}; +use style::values::computed::image::{EndingShape, LineDirection}; use style::values::generics::NonNegative; +use style::values::generics::background::BackgroundSize; +use style::values::generics::image::{Circle, Ellipse, ShapeExtent}; +use style::values::generics::image::EndingShape as GenericEndingShape; +use style::values::generics::image::GradientItem as GenericGradientItem; use style::values::specified::background::BackgroundRepeatKeyword; -use webrender_api::BorderRadius; +use style::values::specified::position::{X, Y}; +use webrender_api::{BorderDetails, BorderRadius, BorderSide, BorderStyle, ColorF, ExtendMode}; +use webrender_api::{Gradient, GradientStop, LayoutSize, NinePatchBorder, NinePatchBorderSource}; +use webrender_api::{NormalBorder, RadialGradient}; + +/// A helper data structure for gradients. +#[derive(Clone, Copy)] +struct StopRun { + start_offset: f32, + end_offset: f32, + start_index: usize, + stop_count: usize, +} /// Placment information for both image and gradient backgrounds. #[derive(Clone, Copy, Debug)] @@ -39,6 +68,19 @@ pub struct BackgroundPlacement { pub fixed: bool, } +trait ResolvePercentage { + fn resolve(&self, length: u32) -> u32; +} + +impl ResolvePercentage for NumberOrPercentage { + fn resolve(&self, length: u32) -> u32 { + match *self { + NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, + NumberOrPercentage::Number(n) => n.round() as u32, + } + } +} + /// Access element at index modulo the array length. /// /// Obviously it does not work with empty arrays. @@ -52,14 +94,14 @@ pub fn get_cyclic(arr: &[T], index: usize) -> &T { /// For a given area and an image compute how big the /// image should be displayed on the background. fn compute_background_image_size( - bg_size: BackgroundSize, + bg_size: ComputedBackgroundSize, bounds_size: Size2D, intrinsic_size: Option>, ) -> Size2D { match intrinsic_size { None => match bg_size { - GenericBackgroundSize::Cover | GenericBackgroundSize::Contain => bounds_size, - GenericBackgroundSize::Explicit { width, height } => Size2D::new( + BackgroundSize::Cover | BackgroundSize::Contain => bounds_size, + BackgroundSize::Explicit { width, height } => Size2D::new( MaybeAuto::from_style(width.0, bounds_size.width) .specified_or_default(bounds_size.width), MaybeAuto::from_style(height.0, bounds_size.height) @@ -73,20 +115,16 @@ fn compute_background_image_size( let bounds_aspect_ratio = bounds_size.width.to_f32_px() / bounds_size.height.to_f32_px(); match (bg_size, image_aspect_ratio < bounds_aspect_ratio) { - (GenericBackgroundSize::Contain, false) | (GenericBackgroundSize::Cover, true) => { - Size2D::new( - bounds_size.width, - bounds_size.width.scale_by(image_aspect_ratio.recip()), - ) - }, - (GenericBackgroundSize::Contain, true) | (GenericBackgroundSize::Cover, false) => { - Size2D::new( - bounds_size.height.scale_by(image_aspect_ratio), - bounds_size.height, - ) - }, + (BackgroundSize::Contain, false) | (BackgroundSize::Cover, true) => Size2D::new( + bounds_size.width, + bounds_size.width.scale_by(image_aspect_ratio.recip()), + ), + (BackgroundSize::Contain, true) | (BackgroundSize::Cover, false) => Size2D::new( + bounds_size.height.scale_by(image_aspect_ratio), + bounds_size.height, + ), ( - GenericBackgroundSize::Explicit { + BackgroundSize::Explicit { width, height: NonNegative(LengthOrPercentageOrAuto::Auto), }, @@ -97,7 +135,7 @@ fn compute_background_image_size( Size2D::new(width, width.scale_by(image_aspect_ratio.recip())) }, ( - GenericBackgroundSize::Explicit { + BackgroundSize::Explicit { width: NonNegative(LengthOrPercentageOrAuto::Auto), height, }, @@ -107,7 +145,7 @@ fn compute_background_image_size( .specified_or_default(own_size.height); Size2D::new(height.scale_by(image_aspect_ratio), height) }, - (GenericBackgroundSize::Explicit { width, height }, _) => Size2D::new( + (BackgroundSize::Explicit { width, height }, _) => Size2D::new( MaybeAuto::from_style(width.0, bounds_size.width) .specified_or_default(own_size.width), MaybeAuto::from_style(height.0, bounds_size.height) @@ -118,8 +156,7 @@ fn compute_background_image_size( } } -/// Compute a rounded clip rect for the background. -pub fn clip( +pub fn compute_background_clip( bg_clip: BackgroundClip, absolute_bounds: Rect, border: SideOffsets2D, @@ -130,11 +167,11 @@ pub fn clip( BackgroundClip::BorderBox => (absolute_bounds, border_radii), BackgroundClip::PaddingBox => ( absolute_bounds.inner_rect(border), - border::inner_radii(border_radii, border), + calculate_inner_border_radii(border_radii, border), ), BackgroundClip::ContentBox => ( absolute_bounds.inner_rect(border_padding), - border::inner_radii(border_radii, border_padding), + calculate_inner_border_radii(border_radii, border_padding), ), } } @@ -143,7 +180,7 @@ pub fn clip( /// /// Photos have their resolution as intrinsic size while gradients have /// no intrinsic size. -pub fn placement( +pub fn compute_background_placement( bg: &Background, viewport_size: Size2D, absolute_bounds: Rect, @@ -161,7 +198,7 @@ pub fn placement( let bg_repeat = get_cyclic(&bg.background_repeat.0, index); let bg_size = *get_cyclic(&bg.background_size.0, index); - let (clip_rect, clip_radii) = clip( + let (clip_rect, clip_radii) = compute_background_clip( bg_clip, absolute_bounds, border, @@ -337,3 +374,473 @@ fn tile_image_axis( }, } } + +/// Determines the radius of a circle if it was not explictly provided. +/// +fn convert_circle_size_keyword( + keyword: ShapeExtent, + size: &Size2D, + center: &Point2D, +) -> Size2D { + let radius = match keyword { + ShapeExtent::ClosestSide | ShapeExtent::Contain => { + let dist = get_distance_to_sides(size, center, ::std::cmp::min); + ::std::cmp::min(dist.width, dist.height) + }, + ShapeExtent::FarthestSide => { + let dist = get_distance_to_sides(size, center, ::std::cmp::max); + ::std::cmp::max(dist.width, dist.height) + }, + ShapeExtent::ClosestCorner => get_distance_to_corner(size, center, ::std::cmp::min), + ShapeExtent::FarthestCorner | ShapeExtent::Cover => { + get_distance_to_corner(size, center, ::std::cmp::max) + }, + }; + Size2D::new(radius, radius) +} + +/// Returns the radius for an ellipse with the same ratio as if it was matched to the sides. +fn get_ellipse_radius(size: &Size2D, center: &Point2D, cmp: F) -> Size2D +where + F: Fn(Au, Au) -> Au, +{ + let dist = get_distance_to_sides(size, center, cmp); + Size2D::new( + dist.width.scale_by(::std::f32::consts::FRAC_1_SQRT_2 * 2.0), + dist.height + .scale_by(::std::f32::consts::FRAC_1_SQRT_2 * 2.0), + ) +} + +/// Determines the radius of an ellipse if it was not explictly provided. +/// +fn convert_ellipse_size_keyword( + keyword: ShapeExtent, + size: &Size2D, + center: &Point2D, +) -> Size2D { + match keyword { + ShapeExtent::ClosestSide | ShapeExtent::Contain => { + get_distance_to_sides(size, center, ::std::cmp::min) + }, + ShapeExtent::FarthestSide => get_distance_to_sides(size, center, ::std::cmp::max), + ShapeExtent::ClosestCorner => get_ellipse_radius(size, center, ::std::cmp::min), + ShapeExtent::FarthestCorner | ShapeExtent::Cover => { + get_ellipse_radius(size, center, ::std::cmp::max) + }, + } +} + +fn convert_gradient_stops( + style: &ComputedValues, + gradient_items: &[GradientItem], + total_length: Au, +) -> Vec { + // Determine the position of each stop per CSS-IMAGES § 3.4. + + // Only keep the color stops, discard the color interpolation hints. + let mut stop_items = gradient_items + .iter() + .filter_map(|item| match *item { + GenericGradientItem::ColorStop(ref stop) => Some(*stop), + _ => None, + }).collect::>(); + + assert!(stop_items.len() >= 2); + + // Run the algorithm from + // https://drafts.csswg.org/css-images-3/#color-stop-syntax + + // Step 1: + // If the first color stop does not have a position, set its position to 0%. + { + let first = stop_items.first_mut().unwrap(); + if first.position.is_none() { + first.position = Some(LengthOrPercentage::Percentage(Percentage(0.0))); + } + } + // If the last color stop does not have a position, set its position to 100%. + { + let last = stop_items.last_mut().unwrap(); + if last.position.is_none() { + last.position = Some(LengthOrPercentage::Percentage(Percentage(1.0))); + } + } + + // Step 2: Move any stops placed before earlier stops to the + // same position as the preceding stop. + let mut last_stop_position = stop_items.first().unwrap().position.unwrap(); + for stop in stop_items.iter_mut().skip(1) { + if let Some(pos) = stop.position { + if position_to_offset(last_stop_position, total_length) > + position_to_offset(pos, total_length) + { + stop.position = Some(last_stop_position); + } + last_stop_position = stop.position.unwrap(); + } + } + + // Step 3: Evenly space stops without position. + let mut stops = Vec::with_capacity(stop_items.len()); + let mut stop_run = None; + for (i, stop) in stop_items.iter().enumerate() { + let offset = match stop.position { + None => { + if stop_run.is_none() { + // Initialize a new stop run. + // `unwrap()` here should never fail because this is the beginning of + // a stop run, which is always bounded by a length or percentage. + let start_offset = + position_to_offset(stop_items[i - 1].position.unwrap(), total_length); + // `unwrap()` here should never fail because this is the end of + // a stop run, which is always bounded by a length or percentage. + let (end_index, end_stop) = stop_items[(i + 1)..] + .iter() + .enumerate() + .find(|&(_, ref stop)| stop.position.is_some()) + .unwrap(); + let end_offset = position_to_offset(end_stop.position.unwrap(), total_length); + stop_run = Some(StopRun { + start_offset, + end_offset, + start_index: i - 1, + stop_count: end_index, + }) + } + + let stop_run = stop_run.unwrap(); + let stop_run_length = stop_run.end_offset - stop_run.start_offset; + stop_run.start_offset + + stop_run_length * (i - stop_run.start_index) as f32 / + ((2 + stop_run.stop_count) as f32) + }, + Some(position) => { + stop_run = None; + position_to_offset(position, total_length) + }, + }; + assert!(offset.is_finite()); + stops.push(GradientStop { + offset: offset, + color: style.resolve_color(stop.color).to_layout(), + }) + } + stops +} + +fn as_gradient_extend_mode(repeating: bool) -> ExtendMode { + if repeating { + ExtendMode::Repeat + } else { + ExtendMode::Clamp + } +} + +pub fn convert_linear_gradient( + style: &ComputedValues, + size: Size2D, + stops: &[GradientItem], + direction: LineDirection, + repeating: bool, +) -> (Gradient, Vec) { + let angle = match direction { + LineDirection::Angle(angle) => angle.radians(), + LineDirection::Horizontal(x) => match x { + X::Left => Angle::Deg(270.).radians(), + X::Right => Angle::Deg(90.).radians(), + }, + LineDirection::Vertical(y) => match y { + Y::Top => Angle::Deg(0.).radians(), + Y::Bottom => Angle::Deg(180.).radians(), + }, + LineDirection::Corner(horizontal, vertical) => { + // This the angle for one of the diagonals of the box. Our angle + // will either be this one, this one + PI, or one of the other + // two perpendicular angles. + let atan = (size.height.to_f32_px() / size.width.to_f32_px()).atan(); + match (horizontal, vertical) { + (X::Right, Y::Bottom) => ::std::f32::consts::PI - atan, + (X::Left, Y::Bottom) => ::std::f32::consts::PI + atan, + (X::Right, Y::Top) => atan, + (X::Left, Y::Top) => -atan, + } + }, + }; + + // Get correct gradient line length, based on: + // https://drafts.csswg.org/css-images-3/#linear-gradients + let dir = Point2D::new(angle.sin(), -angle.cos()); + + let line_length = + (dir.x * size.width.to_f32_px()).abs() + (dir.y * size.height.to_f32_px()).abs(); + + let inv_dir_length = 1.0 / (dir.x * dir.x + dir.y * dir.y).sqrt(); + + // This is the vector between the center and the ending point; i.e. half + // of the distance between the starting point and the ending point. + let delta = Vector2D::new( + Au::from_f32_px(dir.x * inv_dir_length * line_length / 2.0), + Au::from_f32_px(dir.y * inv_dir_length * line_length / 2.0), + ); + + // This is the length of the gradient line. + let length = Au::from_f32_px((delta.x.to_f32_px() * 2.0).hypot(delta.y.to_f32_px() * 2.0)); + + let stops = convert_gradient_stops(style, stops, length); + + let center = Point2D::new(size.width / 2, size.height / 2); + + ( + Gradient { + start_point: (center - delta).to_layout(), + end_point: (center + delta).to_layout(), + extend_mode: as_gradient_extend_mode(repeating), + }, + stops, + ) +} + +pub fn convert_radial_gradient( + style: &ComputedValues, + size: Size2D, + stops: &[GradientItem], + shape: EndingShape, + center: Position, + repeating: bool, +) -> (RadialGradient, Vec) { + let center = Point2D::new( + center.horizontal.to_used_value(size.width), + center.vertical.to_used_value(size.height), + ); + let radius = match shape { + GenericEndingShape::Circle(Circle::Radius(length)) => { + let length = Au::from(length); + Size2D::new(length, length) + }, + GenericEndingShape::Circle(Circle::Extent(extent)) => { + convert_circle_size_keyword(extent, &size, ¢er) + }, + GenericEndingShape::Ellipse(Ellipse::Radii(x, y)) => { + Size2D::new(x.to_used_value(size.width), y.to_used_value(size.height)) + }, + GenericEndingShape::Ellipse(Ellipse::Extent(extent)) => { + convert_ellipse_size_keyword(extent, &size, ¢er) + }, + }; + + let stops = convert_gradient_stops(style, stops, radius.width); + + ( + RadialGradient { + center: center.to_layout(), + radius: radius.to_layout(), + extend_mode: as_gradient_extend_mode(repeating), + // FIXME(pyfisch): These values are calculated by WR. + start_offset: 0.0, + end_offset: 0.0, + }, + stops, + ) +} + +/// Returns the the distance to the nearest or farthest corner depending on the comperator. +fn get_distance_to_corner(size: &Size2D, center: &Point2D, cmp: F) -> Au +where + F: Fn(Au, Au) -> Au, +{ + let dist = get_distance_to_sides(size, center, cmp); + Au::from_f32_px(dist.width.to_f32_px().hypot(dist.height.to_f32_px())) +} + +/// Returns the distance to the nearest or farthest sides depending on the comparator. +/// +/// The first return value is horizontal distance the second vertical distance. +fn get_distance_to_sides(size: &Size2D, center: &Point2D, cmp: F) -> Size2D +where + F: Fn(Au, Au) -> Au, +{ + let top_side = center.y; + let right_side = size.width - center.x; + let bottom_side = size.height - center.y; + let left_side = center.x; + Size2D::new(cmp(left_side, right_side), cmp(top_side, bottom_side)) +} + +fn position_to_offset(position: LengthOrPercentage, total_length: Au) -> f32 { + if total_length == Au(0) { + return 0.0; + } + match position { + LengthOrPercentage::Length(l) => l.to_i32_au() as f32 / total_length.0 as f32, + LengthOrPercentage::Percentage(percentage) => percentage.0 as f32, + LengthOrPercentage::Calc(calc) => { + calc.to_used_value(Some(total_length)).unwrap().0 as f32 / total_length.0 as f32 + }, + } +} + +fn scale_border_radii(radii: BorderRadius, factor: f32) -> BorderRadius { + BorderRadius { + top_left: radii.top_left * factor, + top_right: radii.top_right * factor, + bottom_left: radii.bottom_left * factor, + bottom_right: radii.bottom_right * factor, + } +} + +fn handle_overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { + // No two corners' border radii may add up to more than the length of the edge + // between them. To prevent that, all radii are scaled down uniformly. + fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { + let required = radius_a + radius_b; + + if required <= edge_length { + 1.0 + } else { + edge_length / required + } + } + + let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); + let bottom_factor = scale_factor( + radii.bottom_left.width, + radii.bottom_right.width, + size.width, + ); + let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); + let right_factor = scale_factor( + radii.top_right.height, + radii.bottom_right.height, + size.height, + ); + let min_factor = top_factor + .min(bottom_factor) + .min(left_factor) + .min(right_factor); + if min_factor < 1.0 { + scale_border_radii(radii, min_factor) + } else { + radii + } +} + +pub fn build_border_radius( + abs_bounds: Rect, + border_style: &style_structs::Border, +) -> BorderRadius { + // TODO(cgaebel): Support border radii even in the case of multiple border widths. + // This is an extension of supporting elliptical radii. For now, all percentage + // radii will be relative to the width. + + handle_overlapping_radii( + abs_bounds.size.to_layout(), + BorderRadius { + top_left: model::specified_border_radius( + border_style.border_top_left_radius, + abs_bounds.size, + ).to_layout(), + top_right: model::specified_border_radius( + border_style.border_top_right_radius, + abs_bounds.size, + ).to_layout(), + bottom_right: model::specified_border_radius( + border_style.border_bottom_right_radius, + abs_bounds.size, + ).to_layout(), + bottom_left: model::specified_border_radius( + border_style.border_bottom_left_radius, + abs_bounds.size, + ).to_layout(), + }, + ) +} + +/// Creates a four-sided border with uniform color, width and corner radius. +pub fn simple_normal_border(color: ColorF, style: BorderStyle) -> NormalBorder { + let side = BorderSide { color, style }; + NormalBorder { + left: side, + right: side, + top: side, + bottom: side, + radius: BorderRadius::zero(), + } +} + +/// Calculates radii for the inner side. +/// +/// Radii usually describe the outer side of a border but for the lines to look nice +/// the inner radii need to be smaller depending on the line width. +/// +/// This is used to determine clipping areas. +pub fn calculate_inner_border_radii( + mut radii: BorderRadius, + offsets: SideOffsets2D, +) -> BorderRadius { + fn inner_length(x: f32, offset: Au) -> f32 { + 0.0_f32.max(x - offset.to_f32_px()) + } + radii.top_left.width = inner_length(radii.top_left.width, offsets.left); + radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); + + radii.top_right.width = inner_length(radii.top_right.width, offsets.right); + radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); + + radii.top_left.height = inner_length(radii.top_left.height, offsets.top); + radii.top_right.height = inner_length(radii.top_right.height, offsets.top); + + radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); + radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); + radii +} + +/// Given an image and a border style constructs a border image. +/// +/// See: https://drafts.csswg.org/css-backgrounds-3/#border-images +pub fn build_image_border_details( + webrender_image: WebRenderImageInfo, + border_style_struct: &style_structs::Border, + outset: SideOffsets2D, +) -> Option { + let corners = &border_style_struct.border_image_slice.offsets; + let border_image_repeat = &border_style_struct.border_image_repeat; + if let Some(image_key) = webrender_image.key { + Some(BorderDetails::NinePatch(NinePatchBorder { + source: NinePatchBorderSource::Image(image_key), + width: webrender_image.width, + height: webrender_image.height, + slice: SideOffsets2D::new( + corners.0.resolve(webrender_image.height), + corners.1.resolve(webrender_image.width), + corners.2.resolve(webrender_image.height), + corners.3.resolve(webrender_image.width), + ), + fill: border_style_struct.border_image_slice.fill, + repeat_horizontal: border_image_repeat.0.to_layout(), + repeat_vertical: border_image_repeat.1.to_layout(), + outset: outset, + })) + } else { + None + } +} + +fn calculate_border_image_outset_side(outset: LengthOrNumber, border_width: Au) -> Au { + match outset { + Either::First(length) => length.into(), + Either::Second(factor) => border_width.scale_by(factor), + } +} + +pub fn calculate_border_image_outset( + outset: BorderImageOutset, + border: SideOffsets2D, +) -> SideOffsets2D { + SideOffsets2D::new( + calculate_border_image_outset_side(outset.0, border.top), + calculate_border_image_outset_side(outset.1, border.right), + calculate_border_image_outset_side(outset.2, border.bottom), + calculate_border_image_outset_side(outset.3, border.left), + ) +} diff --git a/components/layout/display_list/border.rs b/components/layout/display_list/border.rs deleted file mode 100644 index a70fc2bb452b..000000000000 --- a/components/layout/display_list/border.rs +++ /dev/null @@ -1,202 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// FIXME(rust-lang/rust#26264): Remove GenericBorderImageSideWidth. - -use app_units::Au; -use crate::display_list::ToLayout; -use euclid::{Rect, SideOffsets2D, Size2D}; -use style::computed_values::border_image_outset::T as BorderImageOutset; -use style::properties::style_structs::Border; -use style::values::computed::NumberOrPercentage; -use style::values::computed::{BorderCornerRadius, BorderImageWidth}; -use style::values::computed::{BorderImageSideWidth, LengthOrNumber}; -use style::values::generics::border::BorderImageSideWidth as GenericBorderImageSideWidth; -use style::values::generics::rect::Rect as StyleRect; -use style::values::Either; -use webrender_api::{BorderRadius, BorderSide, BorderStyle, ColorF}; -use webrender_api::{LayoutSideOffsets, LayoutSize, NormalBorder}; - -/// Computes a border radius size against the containing size. -/// -/// Note that percentages in `border-radius` are resolved against the relevant -/// box dimension instead of only against the width per [1]: -/// -/// > Percentages: Refer to corresponding dimension of the border box. -/// -/// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius -fn corner_radius(radius: BorderCornerRadius, containing_size: Size2D) -> Size2D { - let w = radius.0.width().to_used_value(containing_size.width); - let h = radius.0.height().to_used_value(containing_size.height); - Size2D::new(w, h) -} - -fn scaled_radii(radii: BorderRadius, factor: f32) -> BorderRadius { - BorderRadius { - top_left: radii.top_left * factor, - top_right: radii.top_right * factor, - bottom_left: radii.bottom_left * factor, - bottom_right: radii.bottom_right * factor, - } -} - -fn overlapping_radii(size: LayoutSize, radii: BorderRadius) -> BorderRadius { - // No two corners' border radii may add up to more than the length of the edge - // between them. To prevent that, all radii are scaled down uniformly. - fn scale_factor(radius_a: f32, radius_b: f32, edge_length: f32) -> f32 { - let required = radius_a + radius_b; - - if required <= edge_length { - 1.0 - } else { - edge_length / required - } - } - - let top_factor = scale_factor(radii.top_left.width, radii.top_right.width, size.width); - let bottom_factor = scale_factor( - radii.bottom_left.width, - radii.bottom_right.width, - size.width, - ); - let left_factor = scale_factor(radii.top_left.height, radii.bottom_left.height, size.height); - let right_factor = scale_factor( - radii.top_right.height, - radii.bottom_right.height, - size.height, - ); - let min_factor = top_factor - .min(bottom_factor) - .min(left_factor) - .min(right_factor); - if min_factor < 1.0 { - scaled_radii(radii, min_factor) - } else { - radii - } -} - -/// Determine the four corner radii of a border. -/// -/// Radii may either be absolute or relative to the absolute bounds. -/// Each corner radius has a width and a height which may differ. -/// Lastly overlapping radii are shrank so they don't collide anymore. -pub fn radii(abs_bounds: Rect, border_style: &Border) -> BorderRadius { - // TODO(cgaebel): Support border radii even in the case of multiple border widths. - // This is an extension of supporting elliptical radii. For now, all percentage - // radii will be relative to the width. - - overlapping_radii( - abs_bounds.size.to_layout(), - BorderRadius { - top_left: corner_radius(border_style.border_top_left_radius, abs_bounds.size) - .to_layout(), - top_right: corner_radius(border_style.border_top_right_radius, abs_bounds.size) - .to_layout(), - bottom_right: corner_radius(border_style.border_bottom_right_radius, abs_bounds.size) - .to_layout(), - bottom_left: corner_radius(border_style.border_bottom_left_radius, abs_bounds.size) - .to_layout(), - }, - ) -} - -/// Calculates radii for the inner side. -/// -/// Radii usually describe the outer side of a border but for the lines to look nice -/// the inner radii need to be smaller depending on the line width. -/// -/// This is used to determine clipping areas. -pub fn inner_radii(mut radii: BorderRadius, offsets: SideOffsets2D) -> BorderRadius { - fn inner_length(x: f32, offset: Au) -> f32 { - 0.0_f32.max(x - offset.to_f32_px()) - } - radii.top_left.width = inner_length(radii.top_left.width, offsets.left); - radii.bottom_left.width = inner_length(radii.bottom_left.width, offsets.left); - - radii.top_right.width = inner_length(radii.top_right.width, offsets.right); - radii.bottom_right.width = inner_length(radii.bottom_right.width, offsets.right); - - radii.top_left.height = inner_length(radii.top_left.height, offsets.top); - radii.top_right.height = inner_length(radii.top_right.height, offsets.top); - - radii.bottom_left.height = inner_length(radii.bottom_left.height, offsets.bottom); - radii.bottom_right.height = inner_length(radii.bottom_right.height, offsets.bottom); - radii -} - -/// Creates a four-sided border with square corners and uniform color and width. -pub fn simple(color: ColorF, style: BorderStyle) -> NormalBorder { - let side = BorderSide { color, style }; - NormalBorder { - left: side, - right: side, - top: side, - bottom: side, - radius: BorderRadius::zero(), - do_aa: true, - } -} - -fn side_image_outset(outset: LengthOrNumber, border_width: Au) -> Au { - match outset { - Either::First(length) => length.into(), - Either::Second(factor) => border_width.scale_by(factor), - } -} - -/// Compute the additional border-image area. -pub fn image_outset(outset: BorderImageOutset, border: SideOffsets2D) -> SideOffsets2D { - SideOffsets2D::new( - side_image_outset(outset.0, border.top), - side_image_outset(outset.1, border.right), - side_image_outset(outset.2, border.bottom), - side_image_outset(outset.3, border.left), - ) -} - -fn side_image_width( - border_image_width: BorderImageSideWidth, - border_width: f32, - total_length: Au, -) -> f32 { - match border_image_width { - GenericBorderImageSideWidth::Length(v) => v.to_used_value(total_length).to_f32_px(), - GenericBorderImageSideWidth::Number(x) => border_width * x, - GenericBorderImageSideWidth::Auto => border_width, - } -} - -pub fn image_width( - width: &BorderImageWidth, - border: LayoutSideOffsets, - border_area: Size2D, -) -> LayoutSideOffsets { - LayoutSideOffsets::new( - side_image_width(width.0, border.top, border_area.height), - side_image_width(width.1, border.right, border_area.width), - side_image_width(width.2, border.bottom, border_area.height), - side_image_width(width.3, border.left, border_area.width), - ) -} - -fn resolve_percentage(value: NumberOrPercentage, length: u32) -> u32 { - match value { - NumberOrPercentage::Percentage(p) => (p.0 * length as f32).round() as u32, - NumberOrPercentage::Number(n) => n.round() as u32, - } -} - -pub fn image_slice( - border_image_slice: &StyleRect, - width: u32, - height: u32, -) -> SideOffsets2D { - SideOffsets2D::new( - resolve_percentage(border_image_slice.0, height), - resolve_percentage(border_image_slice.1, width), - resolve_percentage(border_image_slice.2, height), - resolve_percentage(border_image_slice.3, width), - ) -} diff --git a/components/layout/display_list/builder.rs b/components/layout/display_list/builder.rs index a57f9292bb1c..4a9a77a7fb11 100644 --- a/components/layout/display_list/builder.rs +++ b/components/layout/display_list/builder.rs @@ -8,37 +8,40 @@ //! list building, as the actual painting does not happen here—only deciding *what* we're going to //! paint. +#![deny(unsafe_code)] + use app_units::{Au, AU_PER_PX}; +use block::BlockFlow; use canvas_traits::canvas::{CanvasMsg, FromLayoutMsg}; -use crate::block::BlockFlow; -use crate::context::LayoutContext; -use crate::display_list::background::{self, get_cyclic}; -use crate::display_list::border; -use crate::display_list::gradient; -use crate::display_list::items::{BaseDisplayItem, ClipScrollNode, BLUR_INFLATION_FACTOR}; -use crate::display_list::items::{ClipScrollNodeIndex, ClipScrollNodeType, ClippingAndScrolling}; -use crate::display_list::items::{ClippingRegion, DisplayItem, DisplayItemMetadata, DisplayList}; -use crate::display_list::items::{CommonDisplayItem, DisplayListSection}; -use crate::display_list::items::{IframeDisplayItem, OpaqueNode}; -use crate::display_list::items::{PopAllTextShadowsDisplayItem, PushTextShadowDisplayItem}; -use crate::display_list::items::{StackingContext, StackingContextType, StickyFrameData}; -use crate::display_list::items::{TextOrientation, WebRenderImageInfo}; -use crate::display_list::ToLayout; -use crate::flex::FlexFlow; -use crate::flow::{BaseFlow, Flow, FlowFlags}; -use crate::flow_ref::FlowRef; -use crate::fragment::SpecificFragmentInfo; -use crate::fragment::{CanvasFragmentSource, CoordinateSystem, Fragment, ScannedTextFragmentInfo}; -use crate::inline::{InlineFlow, InlineFragmentNodeFlags}; -use crate::list_item::ListItemFlow; -use crate::model::MaybeAuto; -use crate::table_cell::CollapsedBordersForCell; +use context::LayoutContext; +use display_list::ToLayout; +use display_list::background::{build_border_radius, build_image_border_details}; +use display_list::background::{calculate_border_image_outset, calculate_inner_border_radii}; +use display_list::background::{compute_background_clip, compute_background_placement}; +use display_list::background::{convert_linear_gradient, convert_radial_gradient, get_cyclic}; +use display_list::background::simple_normal_border; +use display_list::items::{BaseDisplayItem, BLUR_INFLATION_FACTOR, ClipScrollNode}; +use display_list::items::{ClipScrollNodeIndex, ClipScrollNodeType, ClippingAndScrolling}; +use display_list::items::{ClippingRegion, DisplayItem, DisplayItemMetadata, DisplayList}; +use display_list::items::{DisplayListSection, CommonDisplayItem}; +use display_list::items::{IframeDisplayItem, LineDisplayItem, OpaqueNode}; +use display_list::items::{PopAllTextShadowsDisplayItem, PushTextShadowDisplayItem}; +use display_list::items::{StackingContext, StackingContextType, StickyFrameData}; +use display_list::items::{TextOrientation, WebRenderImageInfo}; use euclid::{rect, Point2D, Rect, SideOffsets2D, Size2D, TypedSize2D, Vector2D}; +use flex::FlexFlow; +use flow::{BaseFlow, Flow, FlowFlags}; +use flow_ref::FlowRef; use fnv::FnvHashMap; -use gfx::text::glyph::ByteIndex; +use fragment::{CanvasFragmentSource, CoordinateSystem, Fragment, ScannedTextFragmentInfo}; +use fragment::SpecificFragmentInfo; use gfx::text::TextRun; +use gfx::text::glyph::ByteIndex; use gfx_traits::{combine_id_with_fragment_type, FragmentType, StackingContextId}; +use inline::{InlineFlow, InlineFragmentNodeFlags}; use ipc_channel::ipc; +use list_item::ListItemFlow; +use model::MaybeAuto; use msg::constellation_msg::{BrowsingContextId, PipelineId}; use net_traits::image_cache::UsePlaceholder; use range::Range; @@ -56,20 +59,20 @@ use style::computed_values::visibility::T as Visibility; use style::logical_geometry::{LogicalMargin, LogicalPoint, LogicalRect}; use style::properties::{style_structs, ComputedValues}; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::computed::effects::SimpleShadow; -use style::values::computed::image::Image as ComputedImage; +use style::values::{Either, RGBA}; use style::values::computed::Gradient; +use style::values::computed::effects::SimpleShadow; use style::values::generics::background::BackgroundSize; use style::values::generics::image::{GradientKind, Image, PaintWorklet}; use style::values::generics::ui::Cursor; -use style::values::{Either, RGBA}; -use style_traits::cursor::CursorKind; use style_traits::CSSPixel; use style_traits::ToCss; +use style_traits::cursor::CursorKind; +use table_cell::CollapsedBordersForCell; use webrender_api::{self, BorderDetails, BorderRadius, BorderSide, BoxShadowClipMode, ColorF}; use webrender_api::{ExternalScrollId, FilterOp, GlyphInstance, ImageRendering, LayoutRect}; -use webrender_api::{LayoutSize, LayoutTransform, LayoutVector2D, LineStyle, NinePatchBorder}; -use webrender_api::{NinePatchBorderSource, NormalBorder, ScrollSensitivity, StickyOffsetBounds}; +use webrender_api::{LayoutSize, LayoutTransform, LayoutVector2D, LineStyle, NormalBorder}; +use webrender_api::{StickyOffsetBounds, ScrollSensitivity}; fn establishes_containing_block_for_absolute( flags: StackingContextCollectionFlags, @@ -663,19 +666,6 @@ pub trait FragmentDisplayListBuilding { clip: Rect, ); - /// Add display item for image border. - /// - /// Returns `Some` if the addition was successful. - fn build_display_list_for_border_image( - &self, - state: &mut DisplayListBuildState, - style: &ComputedValues, - base: BaseDisplayItem, - bounds: Rect, - image: &ComputedImage, - border_width: SideOffsets2D, - ) -> Option<()>; - /// Adds the display items necessary to paint the outline of this fragment to the display list /// if necessary. fn build_display_list_for_outline_if_applicable( @@ -806,7 +796,7 @@ fn build_border_radius_for_inner_rect( outer_rect: Rect, style: &ComputedValues, ) -> BorderRadius { - let radii = border::radii(outer_rect, style.get_border()); + let radii = build_border_radius(outer_rect, style.get_border()); if radii.is_zero() { return radii; } @@ -815,7 +805,7 @@ fn build_border_radius_for_inner_rect( // border width), we need to adjust to border radius so that we are smaller // rectangle with the same border curve. let border_widths = style.logical_border_width().to_physical(style.writing_mode); - border::inner_radii(radii, border_widths) + calculate_inner_border_radii(radii, border_widths) } impl FragmentDisplayListBuilding for Fragment { @@ -917,12 +907,12 @@ impl FragmentDisplayListBuilding for Fragment { // > with the bottom-most background image layer. let last_background_image_index = background.background_image.0.len() - 1; let color_clip = *get_cyclic(&background.background_clip.0, last_background_image_index); - let (bounds, border_radii) = background::clip( + let (bounds, border_radii) = compute_background_clip( color_clip, absolute_bounds, style.logical_border_width().to_physical(style.writing_mode), self.border_padding.to_physical(self.style.writing_mode), - border::radii(absolute_bounds, style.get_border()), + build_border_radius(absolute_bounds, style.get_border()), ); state.clipping_and_scrolling_scope(|state| { @@ -1041,14 +1031,14 @@ impl FragmentDisplayListBuilding for Fragment { Au::from_px(webrender_image.width as i32), Au::from_px(webrender_image.height as i32), ); - let placement = background::placement( + let placement = compute_background_placement( style.get_background(), state.layout_context.shared_context().viewport_size(), absolute_bounds, Some(image), style.logical_border_width().to_physical(style.writing_mode), self.border_padding.to_physical(self.style.writing_mode), - border::radii(absolute_bounds, style.get_border()), + build_border_radius(absolute_bounds, style.get_border()), index, ); @@ -1077,7 +1067,6 @@ impl FragmentDisplayListBuilding for Fragment { tile_spacing: placement.tile_spacing.to_layout(), image_rendering: style.get_inherited_box().image_rendering.to_layout(), alpha_type: webrender_api::AlphaType::PremultipliedAlpha, - color: webrender_api::ColorF::WHITE, }, ); }); @@ -1152,14 +1141,14 @@ impl FragmentDisplayListBuilding for Fragment { style: &ComputedValues, index: usize, ) { - let placement = background::placement( + let placement = compute_background_placement( style.get_background(), state.layout_context.shared_context().viewport_size(), absolute_bounds, None, style.logical_border_width().to_physical(style.writing_mode), self.border_padding.to_physical(self.style.writing_mode), - border::radii(absolute_bounds, style.get_border()), + build_border_radius(absolute_bounds, style.get_border()), index, ); @@ -1180,7 +1169,7 @@ impl FragmentDisplayListBuilding for Fragment { let display_item = match gradient.kind { GradientKind::Linear(angle_or_corner) => { - let (gradient, stops) = gradient::linear( + let (gradient, stops) = convert_linear_gradient( style, placement.tile_size, &gradient.items[..], @@ -1195,7 +1184,7 @@ impl FragmentDisplayListBuilding for Fragment { DisplayItem::Gradient(CommonDisplayItem::with_data(base, item, stops)) }, GradientKind::Radial(shape, center, _angle) => { - let (gradient, stops) = gradient::radial( + let (gradient, stops) = convert_radial_gradient( style, placement.tile_size, &gradient.items[..], @@ -1241,7 +1230,7 @@ impl FragmentDisplayListBuilding for Fragment { style.get_cursor(CursorKind::Default), display_list_section, ); - let border_radius = border::radii(absolute_bounds, style.get_border()); + let border_radius = build_border_radius(absolute_bounds, style.get_border()); state.add_display_item(DisplayItem::BoxShadow(CommonDisplayItem::new( base, webrender_api::BoxShadowDisplayItem { @@ -1287,6 +1276,10 @@ impl FragmentDisplayListBuilding for Fragment { }, BorderPaintingMode::Hidden => return, } + if border.is_zero() { + // TODO: check if image-border-outset is zero + return; + } let border_style_struct = style.get_border(); let mut colors = SideOffsets2D::new( @@ -1324,158 +1317,117 @@ impl FragmentDisplayListBuilding for Fragment { display_list_section, ); - let border_radius = border::radii(bounds, border_style_struct); + let border_radius = build_border_radius(bounds, border_style_struct); let border_widths = border.to_physical(style.writing_mode); - - if let Either::Second(ref image) = border_style_struct.border_image_source { - if self - .build_display_list_for_border_image( - state, - style, - base.clone(), - bounds, - image, - border_widths, - ) - .is_some() - { - return; - } - // Fallback to rendering a solid border. - } - if border_widths == SideOffsets2D::zero() { - return; - } - let details = BorderDetails::Normal(NormalBorder { - left: BorderSide { - color: style.resolve_color(colors.left).to_layout(), - style: border_style.left.to_layout(), - }, - right: BorderSide { - color: style.resolve_color(colors.right).to_layout(), - style: border_style.right.to_layout(), - }, - top: BorderSide { - color: style.resolve_color(colors.top).to_layout(), - style: border_style.top.to_layout(), - }, - bottom: BorderSide { - color: style.resolve_color(colors.bottom).to_layout(), - style: border_style.bottom.to_layout(), - }, - radius: border_radius, - do_aa: true, - }); - state.add_display_item(DisplayItem::Border(CommonDisplayItem::with_data( - base, - webrender_api::BorderDisplayItem { - widths: border_widths.to_layout(), - details, - }, - Vec::new(), - ))); - } - - fn build_display_list_for_border_image( - &self, - state: &mut DisplayListBuildState, - style: &ComputedValues, - base: BaseDisplayItem, - bounds: Rect, - image: &ComputedImage, - border_width: SideOffsets2D, - ) -> Option<()> { - let border_style_struct = style.get_border(); - let border_image_outset = - border::image_outset(border_style_struct.border_image_outset, border_width); - let border_image_area = bounds.outer_rect(border_image_outset).size; - let border_image_width = border::image_width( - &border_style_struct.border_image_width, - border_width.to_layout(), - border_image_area, + let outset = + calculate_border_image_outset(border_style_struct.border_image_outset, border_widths); + let outset_layout = SideOffsets2D::new( + outset.top.to_f32_px(), + outset.right.to_f32_px(), + outset.bottom.to_f32_px(), + outset.left.to_f32_px(), ); - let border_image_repeat = &border_style_struct.border_image_repeat; - let border_image_fill = border_style_struct.border_image_slice.fill; - let border_image_slice = &border_style_struct.border_image_slice.offsets; + let size = bounds.outer_rect(outset).size; let mut stops = Vec::new(); - let mut width = border_image_area.width.to_px() as u32; - let mut height = border_image_area.height.to_px() as u32; - let source = match image { - Image::Url(ref image_url) => { - let url = image_url.url()?; - let image = state.layout_context.get_webrender_image_for_url( - self.node, - url.clone(), - UsePlaceholder::No, - )?; - width = image.width; - height = image.height; - NinePatchBorderSource::Image(image.key?) - }, - Image::PaintWorklet(ref paint_worklet) => { - let image = self.get_webrender_image_for_paint_worklet( - state, - style, - paint_worklet, - border_image_area, - )?; - width = image.width; - height = image.height; - NinePatchBorderSource::Image(image.key?) - }, - Image::Gradient(ref gradient) => match gradient.kind { + let details = match border_style_struct.border_image_source { + Either::First(_) => Some(BorderDetails::Normal(NormalBorder { + left: BorderSide { + color: style.resolve_color(colors.left).to_layout(), + style: border_style.left.to_layout(), + }, + right: BorderSide { + color: style.resolve_color(colors.right).to_layout(), + style: border_style.right.to_layout(), + }, + top: BorderSide { + color: style.resolve_color(colors.top).to_layout(), + style: border_style.top.to_layout(), + }, + bottom: BorderSide { + color: style.resolve_color(colors.bottom).to_layout(), + style: border_style.bottom.to_layout(), + }, + radius: border_radius, + })), + Either::Second(Image::Gradient(ref gradient)) => Some(match gradient.kind { GradientKind::Linear(angle_or_corner) => { - let (wr_gradient, linear_stops) = gradient::linear( + let (wr_gradient, linear_stops) = convert_linear_gradient( style, - border_image_area, + bounds.size, &gradient.items[..], angle_or_corner, gradient.repeating, ); stops = linear_stops; - NinePatchBorderSource::Gradient(wr_gradient) + BorderDetails::NinePatch(webrender_api::NinePatchBorder { + source: webrender_api::NinePatchBorderSource::Gradient(wr_gradient), + width: 0, + height: 0, + slice: SideOffsets2D::zero(), + fill: false, + repeat_horizontal: webrender_api::RepeatMode::Stretch, + repeat_vertical: webrender_api::RepeatMode::Stretch, + outset: outset_layout, + }) }, GradientKind::Radial(shape, center, _angle) => { - let (wr_gradient, radial_stops) = gradient::radial( + let (wr_gradient, radial_stops) = convert_radial_gradient( style, - border_image_area, + bounds.size, &gradient.items[..], shape, center, gradient.repeating, ); stops = radial_stops; - NinePatchBorderSource::RadialGradient(wr_gradient) + BorderDetails::NinePatch(webrender_api::NinePatchBorder { + source: webrender_api::NinePatchBorderSource::RadialGradient(wr_gradient), + width: 0, + height: 0, + slice: SideOffsets2D::zero(), + fill: false, + repeat_horizontal: webrender_api::RepeatMode::Stretch, + repeat_vertical: webrender_api::RepeatMode::Stretch, + outset: outset_layout, + }) }, + }), + Either::Second(Image::PaintWorklet(ref paint_worklet)) => self + .get_webrender_image_for_paint_worklet(state, style, paint_worklet, size) + .and_then(|image| { + build_image_border_details(image, border_style_struct, outset_layout) + }), + Either::Second(Image::Rect(..)) => { + // TODO: Handle border-image with `-moz-image-rect`. + None }, - _ => return None, - }; - - let details = BorderDetails::NinePatch(NinePatchBorder { - source, - width, - height, - slice: border::image_slice(border_image_slice, width, height), - fill: border_image_fill, - repeat_horizontal: border_image_repeat.0.to_layout(), - repeat_vertical: border_image_repeat.1.to_layout(), - outset: SideOffsets2D::new( - border_image_outset.top.to_f32_px(), - border_image_outset.right.to_f32_px(), - border_image_outset.bottom.to_f32_px(), - border_image_outset.left.to_f32_px(), - ), - }); - state.add_display_item(DisplayItem::Border(CommonDisplayItem::with_data( - base, - webrender_api::BorderDisplayItem { - widths: border_image_width, - details, + Either::Second(Image::Element(..)) => { + // TODO: Handle border-image with `-moz-element`. + None }, - stops, - ))); - Some(()) + Either::Second(Image::Url(ref image_url)) => image_url + .url() + .and_then(|url| { + state.layout_context.get_webrender_image_for_url( + self.node, + url.clone(), + UsePlaceholder::No, + ) + }).and_then(|image| { + build_image_border_details(image, border_style_struct, outset_layout) + }), + }; + if let Some(details) = details { + state.add_display_item(DisplayItem::Border(CommonDisplayItem::with_data( + base, + webrender_api::BorderDisplayItem { + widths: border_widths.to_layout(), + details, + }, + stops, + ))); + } } fn build_display_list_for_outline_if_applicable( @@ -1518,7 +1470,10 @@ impl FragmentDisplayListBuilding for Fragment { base, webrender_api::BorderDisplayItem { widths: SideOffsets2D::new_all_same(width).to_layout(), - details: BorderDetails::Normal(border::simple(color, outline_style.to_layout())), + details: BorderDetails::Normal(simple_normal_border( + color, + outline_style.to_layout(), + )), }, Vec::new(), ))); @@ -1548,7 +1503,7 @@ impl FragmentDisplayListBuilding for Fragment { base, webrender_api::BorderDisplayItem { widths: SideOffsets2D::new_all_same(Au::from_px(1)).to_layout(), - details: BorderDetails::Normal(border::simple( + details: BorderDetails::Normal(simple_normal_border( ColorF::rgb(0, 0, 200), webrender_api::BorderStyle::Solid, )), @@ -1573,17 +1528,11 @@ impl FragmentDisplayListBuilding for Fragment { style.get_cursor(CursorKind::Default), DisplayListSection::Content, ); - // TODO(gw): Use a better estimate for wavy line thickness. - let wavy_line_thickness = (0.33 * base.bounds.size.height).ceil(); - state.add_display_item(DisplayItem::Line(CommonDisplayItem::new( - base, - webrender_api::LineDisplayItem { - orientation: webrender_api::LineOrientation::Horizontal, - wavy_line_thickness, - color: ColorF::rgb(0, 200, 0), - style: LineStyle::Dashed, - }, - ))); + state.add_display_item(DisplayItem::Line(Box::new(LineDisplayItem { + base: base, + color: ColorF::rgb(0, 200, 0), + style: LineStyle::Dashed, + }))); } fn build_debug_borders_around_fragment( @@ -1604,7 +1553,7 @@ impl FragmentDisplayListBuilding for Fragment { base, webrender_api::BorderDisplayItem { widths: SideOffsets2D::new_all_same(Au::from_px(1)).to_layout(), - details: BorderDetails::Normal(border::simple( + details: BorderDetails::Normal(simple_normal_border( ColorF::rgb(0, 0, 200), webrender_api::BorderStyle::Solid, )), @@ -1991,28 +1940,11 @@ impl FragmentDisplayListBuilding for Fragment { .image_rendering .to_layout(), alpha_type: webrender_api::AlphaType::PremultipliedAlpha, - color: webrender_api::ColorF::WHITE, }, ); } } }, - SpecificFragmentInfo::Media(ref fragment_info) => { - if let Some((ref image_key, _, _)) = fragment_info.current_frame { - let base = create_base_display_item(state); - state.add_image_item( - base, - webrender_api::ImageDisplayItem { - image_key: *image_key, - stretch_size: stacking_relative_border_box.size.to_layout(), - tile_spacing: LayoutSize::zero(), - image_rendering: ImageRendering::Auto, - alpha_type: webrender_api::AlphaType::PremultipliedAlpha, - color: webrender_api::ColorF::WHITE, - }, - ); - } - }, SpecificFragmentInfo::Canvas(ref canvas_fragment_info) => { let image_key = match canvas_fragment_info.source { CanvasFragmentSource::WebGL(image_key) => image_key, @@ -2024,8 +1956,7 @@ impl FragmentDisplayListBuilding for Fragment { .send(CanvasMsg::FromLayout( FromLayoutMsg::SendData(sender), canvas_fragment_info.canvas_id.clone(), - )) - .unwrap(); + )).unwrap(); receiver.recv().unwrap().image_key }, None => return, @@ -2039,7 +1970,6 @@ impl FragmentDisplayListBuilding for Fragment { tile_spacing: LayoutSize::zero(), image_rendering: ImageRendering::Auto, alpha_type: webrender_api::AlphaType::PremultipliedAlpha, - color: webrender_api::ColorF::WHITE, }; state.add_image_item(base, display_item); @@ -2142,8 +2072,7 @@ impl FragmentDisplayListBuilding for Fragment { self.style.writing_mode, Au(0), metrics.ascent, - ) - .to_physical(self.style.writing_mode, container_size) + ).to_physical(self.style.writing_mode, container_size) .to_vector(); // Base item for all text/shadows @@ -2278,17 +2207,11 @@ impl FragmentDisplayListBuilding for Fragment { DisplayListSection::Content, ); - // TODO(gw): Use a better estimate for wavy line thickness. - let wavy_line_thickness = (0.33 * base.bounds.size.height).ceil(); - state.add_display_item(DisplayItem::Line(CommonDisplayItem::new( - base, - webrender_api::LineDisplayItem { - orientation: webrender_api::LineOrientation::Horizontal, - wavy_line_thickness, - color: color.to_layout(), - style: LineStyle::Solid, - }, - ))); + state.add_display_item(DisplayItem::Line(Box::new(LineDisplayItem { + base: base, + color: color.to_layout(), + style: LineStyle::Solid, + }))); } fn unique_id(&self) -> u64 { @@ -3214,7 +3137,7 @@ impl BaseFlowDisplayListBuilding for BaseFlow { base, webrender_api::BorderDisplayItem { widths: SideOffsets2D::new_all_same(Au::from_px(2)).to_layout(), - details: BorderDetails::Normal(border::simple( + details: BorderDetails::Normal(simple_normal_border( color, webrender_api::BorderStyle::Solid, )), diff --git a/components/layout/display_list/conversions.rs b/components/layout/display_list/conversions.rs index 39c672539153..b8c5a8e98b6a 100644 --- a/components/layout/display_list/conversions.rs +++ b/components/layout/display_list/conversions.rs @@ -7,10 +7,10 @@ use euclid::{Point2D, Rect, SideOffsets2D, Size2D, Vector2D}; use style::computed_values::image_rendering::T as ImageRendering; use style::computed_values::mix_blend_mode::T as MixBlendMode; use style::computed_values::transform_style::T as TransformStyle; +use style::values::RGBA; use style::values::computed::{BorderStyle, Filter}; use style::values::generics::effects::Filter as GenericFilter; use style::values::specified::border::BorderImageRepeatKeyword; -use style::values::RGBA; use webrender_api as wr; pub trait ToLayout { @@ -129,14 +129,14 @@ impl ToLayout for Rect { } impl ToLayout for SideOffsets2D { - type Type = wr::LayoutSideOffsets; + type Type = wr::BorderWidths; fn to_layout(&self) -> Self::Type { - wr::LayoutSideOffsets::new( - self.top.to_f32_px(), - self.right.to_f32_px(), - self.bottom.to_f32_px(), - self.left.to_f32_px(), - ) + wr::BorderWidths { + left: self.left.to_f32_px(), + top: self.top.to_f32_px(), + right: self.right.to_f32_px(), + bottom: self.bottom.to_f32_px(), + } } } diff --git a/components/layout/display_list/gradient.rs b/components/layout/display_list/gradient.rs deleted file mode 100644 index 5ce61f84615d..000000000000 --- a/components/layout/display_list/gradient.rs +++ /dev/null @@ -1,327 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -// FIXME(rust-lang/rust#26264): Remove GenericEndingShape and GenericGradientItem. - -use app_units::Au; -use crate::display_list::ToLayout; -use euclid::{Point2D, Size2D, Vector2D}; -use style::properties::ComputedValues; -use style::values::computed::image::{EndingShape, LineDirection}; -use style::values::computed::{Angle, GradientItem, LengthOrPercentage, Percentage, Position}; -use style::values::generics::image::EndingShape as GenericEndingShape; -use style::values::generics::image::GradientItem as GenericGradientItem; -use style::values::generics::image::{Circle, Ellipse, ShapeExtent}; -use style::values::specified::position::{X, Y}; -use webrender_api::{ExtendMode, Gradient, GradientBuilder, GradientStop, RadialGradient}; - -/// A helper data structure for gradients. -#[derive(Clone, Copy)] -struct StopRun { - start_offset: f32, - end_offset: f32, - start_index: usize, - stop_count: usize, -} - -/// Determines the radius of a circle if it was not explictly provided. -/// -fn circle_size_keyword( - keyword: ShapeExtent, - size: &Size2D, - center: &Point2D, -) -> Size2D { - let radius = match keyword { - ShapeExtent::ClosestSide | ShapeExtent::Contain => { - let dist = distance_to_sides(size, center, ::std::cmp::min); - ::std::cmp::min(dist.width, dist.height) - }, - ShapeExtent::FarthestSide => { - let dist = distance_to_sides(size, center, ::std::cmp::max); - ::std::cmp::max(dist.width, dist.height) - }, - ShapeExtent::ClosestCorner => distance_to_corner(size, center, ::std::cmp::min), - ShapeExtent::FarthestCorner | ShapeExtent::Cover => { - distance_to_corner(size, center, ::std::cmp::max) - }, - }; - Size2D::new(radius, radius) -} - -/// Returns the radius for an ellipse with the same ratio as if it was matched to the sides. -fn ellipse_radius(size: &Size2D, center: &Point2D, cmp: F) -> Size2D -where - F: Fn(Au, Au) -> Au, -{ - let dist = distance_to_sides(size, center, cmp); - Size2D::new( - dist.width.scale_by(::std::f32::consts::FRAC_1_SQRT_2 * 2.0), - dist.height - .scale_by(::std::f32::consts::FRAC_1_SQRT_2 * 2.0), - ) -} - -/// Determines the radius of an ellipse if it was not explictly provided. -/// -fn ellipse_size_keyword( - keyword: ShapeExtent, - size: &Size2D, - center: &Point2D, -) -> Size2D { - match keyword { - ShapeExtent::ClosestSide | ShapeExtent::Contain => { - distance_to_sides(size, center, ::std::cmp::min) - }, - ShapeExtent::FarthestSide => distance_to_sides(size, center, ::std::cmp::max), - ShapeExtent::ClosestCorner => ellipse_radius(size, center, ::std::cmp::min), - ShapeExtent::FarthestCorner | ShapeExtent::Cover => { - ellipse_radius(size, center, ::std::cmp::max) - }, - } -} - -fn convert_gradient_stops( - style: &ComputedValues, - gradient_items: &[GradientItem], - total_length: Au, -) -> GradientBuilder { - // Determine the position of each stop per CSS-IMAGES § 3.4. - - // Only keep the color stops, discard the color interpolation hints. - let mut stop_items = gradient_items - .iter() - .filter_map(|item| match *item { - GenericGradientItem::ColorStop(ref stop) => Some(*stop), - _ => None, - }) - .collect::>(); - - assert!(stop_items.len() >= 2); - - // Run the algorithm from - // https://drafts.csswg.org/css-images-3/#color-stop-syntax - - // Step 1: - // If the first color stop does not have a position, set its position to 0%. - { - let first = stop_items.first_mut().unwrap(); - if first.position.is_none() { - first.position = Some(LengthOrPercentage::Percentage(Percentage(0.0))); - } - } - // If the last color stop does not have a position, set its position to 100%. - { - let last = stop_items.last_mut().unwrap(); - if last.position.is_none() { - last.position = Some(LengthOrPercentage::Percentage(Percentage(1.0))); - } - } - - // Step 2: Move any stops placed before earlier stops to the - // same position as the preceding stop. - let mut last_stop_position = stop_items.first().unwrap().position.unwrap(); - for stop in stop_items.iter_mut().skip(1) { - if let Some(pos) = stop.position { - if position_to_offset(last_stop_position, total_length) > - position_to_offset(pos, total_length) - { - stop.position = Some(last_stop_position); - } - last_stop_position = stop.position.unwrap(); - } - } - - // Step 3: Evenly space stops without position. - let mut stops = GradientBuilder::new(); - let mut stop_run = None; - for (i, stop) in stop_items.iter().enumerate() { - let offset = match stop.position { - None => { - if stop_run.is_none() { - // Initialize a new stop run. - // `unwrap()` here should never fail because this is the beginning of - // a stop run, which is always bounded by a length or percentage. - let start_offset = - position_to_offset(stop_items[i - 1].position.unwrap(), total_length); - // `unwrap()` here should never fail because this is the end of - // a stop run, which is always bounded by a length or percentage. - let (end_index, end_stop) = stop_items[(i + 1)..] - .iter() - .enumerate() - .find(|&(_, ref stop)| stop.position.is_some()) - .unwrap(); - let end_offset = position_to_offset(end_stop.position.unwrap(), total_length); - stop_run = Some(StopRun { - start_offset, - end_offset, - start_index: i - 1, - stop_count: end_index, - }) - } - - let stop_run = stop_run.unwrap(); - let stop_run_length = stop_run.end_offset - stop_run.start_offset; - stop_run.start_offset + - stop_run_length * (i - stop_run.start_index) as f32 / - ((2 + stop_run.stop_count) as f32) - }, - Some(position) => { - stop_run = None; - position_to_offset(position, total_length) - }, - }; - assert!(offset.is_finite()); - stops.push(GradientStop { - offset: offset, - color: style.resolve_color(stop.color).to_layout(), - }) - } - stops -} - -fn extend_mode(repeating: bool) -> ExtendMode { - if repeating { - ExtendMode::Repeat - } else { - ExtendMode::Clamp - } -} -/// Returns the the distance to the nearest or farthest corner depending on the comperator. -fn distance_to_corner(size: &Size2D, center: &Point2D, cmp: F) -> Au -where - F: Fn(Au, Au) -> Au, -{ - let dist = distance_to_sides(size, center, cmp); - Au::from_f32_px(dist.width.to_f32_px().hypot(dist.height.to_f32_px())) -} - -/// Returns the distance to the nearest or farthest sides depending on the comparator. -/// -/// The first return value is horizontal distance the second vertical distance. -fn distance_to_sides(size: &Size2D, center: &Point2D, cmp: F) -> Size2D -where - F: Fn(Au, Au) -> Au, -{ - let top_side = center.y; - let right_side = size.width - center.x; - let bottom_side = size.height - center.y; - let left_side = center.x; - Size2D::new(cmp(left_side, right_side), cmp(top_side, bottom_side)) -} - -fn position_to_offset(position: LengthOrPercentage, total_length: Au) -> f32 { - if total_length == Au(0) { - return 0.0; - } - match position { - LengthOrPercentage::Length(l) => l.to_i32_au() as f32 / total_length.0 as f32, - LengthOrPercentage::Percentage(percentage) => percentage.0 as f32, - LengthOrPercentage::Calc(calc) => { - calc.to_used_value(Some(total_length)).unwrap().0 as f32 / total_length.0 as f32 - }, - } -} - -pub fn linear( - style: &ComputedValues, - size: Size2D, - stops: &[GradientItem], - direction: LineDirection, - repeating: bool, -) -> (Gradient, Vec) { - let angle = match direction { - LineDirection::Angle(angle) => angle.radians(), - LineDirection::Horizontal(x) => match x { - X::Left => Angle::from_degrees(270.).radians(), - X::Right => Angle::from_degrees(90.).radians(), - }, - LineDirection::Vertical(y) => match y { - Y::Top => Angle::from_degrees(0.).radians(), - Y::Bottom => Angle::from_degrees(180.).radians(), - }, - LineDirection::Corner(horizontal, vertical) => { - // This the angle for one of the diagonals of the box. Our angle - // will either be this one, this one + PI, or one of the other - // two perpendicular angles. - let atan = (size.height.to_f32_px() / size.width.to_f32_px()).atan(); - match (horizontal, vertical) { - (X::Right, Y::Bottom) => ::std::f32::consts::PI - atan, - (X::Left, Y::Bottom) => ::std::f32::consts::PI + atan, - (X::Right, Y::Top) => atan, - (X::Left, Y::Top) => -atan, - } - }, - }; - - // Get correct gradient line length, based on: - // https://drafts.csswg.org/css-images-3/#linear-gradients - let dir = Point2D::new(angle.sin(), -angle.cos()); - - let line_length = - (dir.x * size.width.to_f32_px()).abs() + (dir.y * size.height.to_f32_px()).abs(); - - let inv_dir_length = 1.0 / (dir.x * dir.x + dir.y * dir.y).sqrt(); - - // This is the vector between the center and the ending point; i.e. half - // of the distance between the starting point and the ending point. - let delta = Vector2D::new( - Au::from_f32_px(dir.x * inv_dir_length * line_length / 2.0), - Au::from_f32_px(dir.y * inv_dir_length * line_length / 2.0), - ); - - // This is the length of the gradient line. - let length = Au::from_f32_px((delta.x.to_f32_px() * 2.0).hypot(delta.y.to_f32_px() * 2.0)); - - let mut builder = convert_gradient_stops(style, stops, length); - - let center = Point2D::new(size.width / 2, size.height / 2); - - ( - builder.gradient( - (center - delta).to_layout(), - (center + delta).to_layout(), - extend_mode(repeating), - ), - builder.stops().to_vec(), - ) -} - -pub fn radial( - style: &ComputedValues, - size: Size2D, - stops: &[GradientItem], - shape: EndingShape, - center: Position, - repeating: bool, -) -> (RadialGradient, Vec) { - let center = Point2D::new( - center.horizontal.to_used_value(size.width), - center.vertical.to_used_value(size.height), - ); - let radius = match shape { - GenericEndingShape::Circle(Circle::Radius(length)) => { - let length = Au::from(length); - Size2D::new(length, length) - }, - GenericEndingShape::Circle(Circle::Extent(extent)) => { - circle_size_keyword(extent, &size, ¢er) - }, - GenericEndingShape::Ellipse(Ellipse::Radii(x, y)) => { - Size2D::new(x.to_used_value(size.width), y.to_used_value(size.height)) - }, - GenericEndingShape::Ellipse(Ellipse::Extent(extent)) => { - ellipse_size_keyword(extent, &size, ¢er) - }, - }; - - let mut builder = convert_gradient_stops(style, stops, radius.width); - ( - builder.radial_gradient( - center.to_layout(), - radius.to_layout(), - extend_mode(repeating), - ), - builder.stops().to_vec(), - ) -} diff --git a/components/layout/display_list/items.rs b/components/layout/display_list/items.rs index f07099c5b07a..51e44e25cdbe 100644 --- a/components/layout/display_list/items.rs +++ b/components/layout/display_list/items.rs @@ -13,8 +13,8 @@ //! low-level drawing primitives. use euclid::{SideOffsets2D, TypedRect, Vector2D}; -use gfx_traits::print_tree::PrintTree; use gfx_traits::{self, StackingContextId}; +use gfx_traits::print_tree::PrintTree; use msg::constellation_msg::PipelineId; use net_traits::image::base::Image; use servo_geometry::MaxRect; @@ -23,10 +23,10 @@ use std::collections::HashMap; use std::f32; use std::fmt; use webrender_api as wr; -use webrender_api::{BorderRadius, ClipMode}; +use webrender_api::{BorderRadius, ClipMode, ColorF}; use webrender_api::{ComplexClipRegion, ExternalScrollId, FilterOp}; use webrender_api::{GlyphInstance, GradientStop, ImageKey, LayoutPoint}; -use webrender_api::{LayoutRect, LayoutSize, LayoutTransform, LayoutVector2D}; +use webrender_api::{LayoutRect, LayoutSize, LayoutTransform, LayoutVector2D, LineStyle}; use webrender_api::{MixBlendMode, ScrollSensitivity, Shadow}; use webrender_api::{StickyOffsetBounds, TransformStyle}; @@ -380,7 +380,7 @@ pub enum DisplayItem { Border(Box>>), Gradient(Box>>), RadialGradient(Box>>), - Line(Box>), + Line(Box), BoxShadow(Box>), PushTextShadow(Box), PopAllTextShadows(Box), @@ -590,8 +590,7 @@ impl ClippingRegion { rect: complex.rect.translate(delta), radii: complex.radii, mode: complex.mode, - }) - .collect(), + }).collect(), } } @@ -679,6 +678,18 @@ pub struct IframeDisplayItem { pub iframe: PipelineId, } +/// Paints a line segment. +#[derive(Clone, Serialize)] +pub struct LineDisplayItem { + pub base: BaseDisplayItem, + + /// The line segment color. + pub color: ColorF, + + /// The line segment style. + pub style: LineStyle, +} + #[derive(Clone, Serialize)] pub struct CommonDisplayItem { pub base: BaseDisplayItem, @@ -854,3 +865,27 @@ impl WebRenderImageInfo { /// The type of the scroll offset list. This is only populated if WebRender is in use. pub type ScrollOffsetMap = HashMap>; + +pub trait SimpleMatrixDetection { + fn is_identity_or_simple_translation(&self) -> bool; +} + +impl SimpleMatrixDetection for LayoutTransform { + #[inline] + fn is_identity_or_simple_translation(&self) -> bool { + let (_0, _1) = (0.0, 1.0); + self.m11 == _1 && + self.m12 == _0 && + self.m13 == _0 && + self.m14 == _0 && + self.m21 == _0 && + self.m22 == _1 && + self.m23 == _0 && + self.m24 == _0 && + self.m31 == _0 && + self.m32 == _0 && + self.m33 == _1 && + self.m34 == _0 && + self.m44 == _1 + } +} diff --git a/components/layout/display_list/mod.rs b/components/layout/display_list/mod.rs index 4ee6f1fde8e2..602a36d400fb 100644 --- a/components/layout/display_list/mod.rs +++ b/components/layout/display_list/mod.rs @@ -15,9 +15,7 @@ pub use self::conversions::ToLayout; pub use self::webrender_helpers::WebRenderDisplayListConverter; mod background; -mod border; mod builder; mod conversions; -mod gradient; pub mod items; mod webrender_helpers; diff --git a/components/layout/display_list/webrender_helpers.rs b/components/layout/display_list/webrender_helpers.rs index 1d98410ed135..43ae47c52418 100644 --- a/components/layout/display_list/webrender_helpers.rs +++ b/components/layout/display_list/webrender_helpers.rs @@ -7,11 +7,11 @@ // This might be achieved by sharing types between WR and Servo display lists, or // completely converting layout to directly generate WebRender display lists, for example. -use crate::display_list::items::{ClipScrollNode, ClipScrollNodeIndex, ClipScrollNodeType}; -use crate::display_list::items::{DisplayItem, DisplayList, StackingContextType}; +use display_list::items::{ClipScrollNode, ClipScrollNodeIndex, ClipScrollNodeType}; +use display_list::items::{DisplayItem, DisplayList, StackingContextType}; use msg::constellation_msg::PipelineId; -use webrender_api::{self, ClipAndScrollInfo, ClipId, DisplayListBuilder, RasterSpace}; -use webrender_api::{LayoutPoint, SpecificDisplayItem}; +use webrender_api::{self, ClipAndScrollInfo, ClipId, DisplayListBuilder, GlyphRasterSpace}; +use webrender_api::LayoutPoint; pub trait WebRenderDisplayListConverter { fn convert_to_webrender(&self, pipeline_id: PipelineId) -> DisplayListBuilder; @@ -104,37 +104,115 @@ impl WebRenderDisplayItemConverter for DisplayItem { match *self { DisplayItem::Rectangle(ref item) => { - builder.push_item(SpecificDisplayItem::Rectangle(item.item), &self.prim_info()); + builder.push_rect(&self.prim_info(), item.item.color); }, DisplayItem::Text(ref item) => { - builder.push_item(SpecificDisplayItem::Text(item.item), &self.prim_info()); - builder.push_iter(item.data.iter()); + builder.push_text( + &self.prim_info(), + &item.data, + item.item.font_key, + item.item.color, + item.item.glyph_options, + ); }, DisplayItem::Image(ref item) => { - builder.push_item(SpecificDisplayItem::Image(item.item), &self.prim_info()); + builder.push_image( + &self.prim_info(), + item.item.stretch_size, + item.item.tile_spacing, + item.item.image_rendering, + item.item.alpha_type, + item.item.image_key, + ); }, DisplayItem::Border(ref item) => { - if !item.data.is_empty() { - builder.push_stops(item.data.as_ref()); + if item.data.is_empty() { + builder.push_border(&self.prim_info(), item.item.widths, item.item.details); + } else { + let mut details = item.item.details.clone(); + match &mut details { + webrender_api::BorderDetails::NinePatch( + webrender_api::NinePatchBorder { + source: + webrender_api::NinePatchBorderSource::Gradient(ref mut gradient), + .. + }, + ) => { + *gradient = builder.create_gradient( + gradient.start_point, + gradient.end_point, + item.data.clone(), + gradient.extend_mode, + ); + }, + webrender_api::BorderDetails::NinePatch( + webrender_api::NinePatchBorder { + source: + webrender_api::NinePatchBorderSource::RadialGradient(gradient), + .. + }, + ) => { + *gradient = builder.create_radial_gradient( + gradient.center, + gradient.radius, + item.data.clone(), + gradient.extend_mode, + ) + }, + _ => unreachable!(), + } + builder.push_border(&self.prim_info(), item.item.widths, details); } - builder.push_item(SpecificDisplayItem::Border(item.item), &self.prim_info()); }, DisplayItem::Gradient(ref item) => { - builder.push_stops(item.data.as_ref()); - builder.push_item(SpecificDisplayItem::Gradient(item.item), &self.prim_info()); + let gradient = builder.create_gradient( + item.item.gradient.start_point, + item.item.gradient.end_point, + item.data.clone(), + item.item.gradient.extend_mode, + ); + builder.push_gradient( + &self.prim_info(), + gradient, + item.item.tile_size, + item.item.tile_spacing, + ); }, DisplayItem::RadialGradient(ref item) => { - builder.push_stops(item.data.as_ref()); - builder.push_item( - SpecificDisplayItem::RadialGradient(item.item), + let gradient = builder.create_radial_gradient( + item.item.gradient.center, + item.item.gradient.radius, + item.data.clone(), + item.item.gradient.extend_mode, + ); + builder.push_radial_gradient( &self.prim_info(), + gradient, + item.item.tile_size, + item.item.tile_spacing, ); }, DisplayItem::Line(ref item) => { - builder.push_item(SpecificDisplayItem::Line(item.item), &self.prim_info()); + builder.push_line( + &self.prim_info(), + // TODO(gw): Use a better estimate for wavy line thickness. + (0.33 * item.base.bounds.size.height).ceil(), + webrender_api::LineOrientation::Horizontal, + &item.color, + item.style, + ); }, DisplayItem::BoxShadow(ref item) => { - builder.push_item(SpecificDisplayItem::BoxShadow(item.item), &self.prim_info()); + builder.push_box_shadow( + &self.prim_info(), + item.item.box_bounds, + item.item.offset, + item.item.color, + item.item.blur_radius, + item.item.spread_radius, + item.item.border_radius, + item.item.clip_mode, + ); }, DisplayItem::PushTextShadow(ref item) => { builder.push_shadow(&self.prim_info(), item.shadow); @@ -173,8 +251,8 @@ impl WebRenderDisplayItemConverter for DisplayItem { None, stacking_context.transform_style, stacking_context.mix_blend_mode, - &stacking_context.filters, - RasterSpace::Screen, + stacking_context.filters.clone(), + GlyphRasterSpace::Screen, ); if stacking_context.established_reference_frame.is_some() { diff --git a/components/layout/flex.rs b/components/layout/flex.rs index fe9d72fa55e9..e1baa3903829 100644 --- a/components/layout/flex.rs +++ b/components/layout/flex.rs @@ -4,19 +4,20 @@ //! Layout for elements with a CSS `display` property of `flex`. +#![deny(unsafe_code)] + use app_units::{Au, MAX_AU}; -use crate::block::{AbsoluteAssignBSizesTraversal, BlockFlow, MarginsMayCollapseFlag}; -use crate::context::LayoutContext; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::{DisplayListBuildState, FlexFlowDisplayListBuilding}; -use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::model::{AdjoiningMargins, CollapsibleMargins}; -use crate::model::{IntrinsicISizes, MaybeAuto, SizeConstraint}; -use crate::traversal::PreorderFlowTraversal; +use block::{AbsoluteAssignBSizesTraversal, BlockFlow, MarginsMayCollapseFlag}; +use context::LayoutContext; +use display_list::{DisplayListBuildState, FlexFlowDisplayListBuilding}; +use display_list::StackingContextCollectionState; use euclid::Point2D; +use floats::FloatKind; +use flow::{Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow, FlowFlags}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; +use layout_debug; +use model::{AdjoiningMargins, CollapsibleMargins}; +use model::{IntrinsicISizes, MaybeAuto, SizeConstraint}; use std::cmp::{max, min}; use std::ops::Range; use style::computed_values::align_content::T as AlignContent; @@ -27,11 +28,10 @@ use style::computed_values::justify_content::T as JustifyContent; use style::logical_geometry::{Direction, LogicalSize}; use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; +use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; use style::values::computed::flex::FlexBasis; -use style::values::computed::{ - LengthOrPercentage, LengthOrPercentageOrAuto, LengthOrPercentageOrNone, -}; use style::values::generics::flex::FlexBasis as GenericFlexBasis; +use traversal::PreorderFlowTraversal; /// The size of an axis. May be a specified size, a min/max /// constraint, or an unlimited size @@ -116,7 +116,7 @@ struct FlexItem { } impl FlexItem { - pub fn new(index: usize, flow: &dyn Flow) -> FlexItem { + pub fn new(index: usize, flow: &Flow) -> FlexItem { let style = &flow.as_block().fragment.style; let flex_grow = style.get_position().flex_grow; let flex_shrink = style.get_position().flex_shrink; @@ -140,7 +140,7 @@ impl FlexItem { /// Initialize the used flex base size, minimal main size and maximal main size. /// For block mode container this method should be called in assign_block_size() /// pass so that the item has already been layouted. - pub fn init_sizes(&mut self, flow: &mut dyn Flow, containing_length: Au, direction: Direction) { + pub fn init_sizes(&mut self, flow: &mut Flow, containing_length: Au, direction: Direction) { let block = flow.as_mut_block(); match direction { // TODO(stshine): the definition of min-{width, height} in style component @@ -207,7 +207,7 @@ impl FlexItem { /// Returns the outer main size of the item, including paddings and margins, /// clamped by max and min size. - pub fn outer_main_size(&self, flow: &dyn Flow, direction: Direction) -> Au { + pub fn outer_main_size(&self, flow: &Flow, direction: Direction) -> Au { let ref fragment = flow.as_block().fragment; let outer_width = match direction { Direction::Inline => { @@ -223,7 +223,7 @@ impl FlexItem { } /// Returns the number of auto margins in given direction. - pub fn auto_margin_count(&self, flow: &dyn Flow, direction: Direction) -> i32 { + pub fn auto_margin_count(&self, flow: &Flow, direction: Direction) -> i32 { let margin = flow.as_block().fragment.style.logical_margin(); let mut margin_count = 0; match direction { @@ -350,7 +350,7 @@ impl FlexLine { } #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for FlexFlow {} +unsafe impl ::flow::HasBaseFlow for FlexFlow {} /// A block with the CSS `display` property equal to `flex`. #[derive(Debug, Serialize)] @@ -577,7 +577,7 @@ impl FlexFlow { debug!("content_inline_size = {:?}", content_inline_size); - let child_count = ImmutableFlowUtils::child_count(self as &dyn Flow) as i32; + let child_count = ImmutableFlowUtils::child_count(self as &Flow) as i32; debug!("child_count = {:?}", child_count); if child_count == 0 { return; @@ -924,8 +924,7 @@ impl Flow for FlexFlow { .base .flags .contains(FlowFlags::IS_ABSOLUTELY_POSITIONED) - }) - .map(|(index, flow)| FlexItem::new(index, flow)) + }).map(|(index, flow)| FlexItem::new(index, flow)) .collect(); items.sort_by_key(|item| item.order); @@ -1055,7 +1054,7 @@ impl Flow for FlexFlow { CollapsibleMargins::Collapse(block_start, block_end); // TODO(stshine): assign proper static position for absolute descendants. - if (&*self as &dyn Flow).contains_roots_of_absolute_flow_tree() { + if (&*self as &Flow).contains_roots_of_absolute_flow_tree() { // Assign block-sizes for all flows in this absolute flow tree. // This is preorder because the block-size of an absolute flow may depend on // the block-size of its containing block, which may also be an absolute flow. @@ -1102,7 +1101,7 @@ impl Flow for FlexFlow { self.block_flow.collect_stacking_contexts(state); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -1124,7 +1123,7 @@ impl Flow for FlexFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -1135,7 +1134,7 @@ impl Flow for FlexFlow { ); } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator); } } diff --git a/components/layout/floats.rs b/components/layout/floats.rs index b054cccceafb..a0f44c22a041 100644 --- a/components/layout/floats.rs +++ b/components/layout/floats.rs @@ -3,9 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use app_units::{Au, MAX_AU}; -use crate::block::FormattingContextType; -use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; -use crate::persistent_list::PersistentList; +use block::FormattingContextType; +use flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; +use persistent_list::PersistentList; use std::cmp::{max, min}; use std::fmt; use style::computed_values::float::T as StyleFloat; @@ -494,7 +494,7 @@ impl SpeculatedFloatPlacement { /// Given the speculated inline size of the floats out for the inorder predecessor of this /// flow, computes the speculated inline size of the floats flowing in. - pub fn compute_floats_in(&mut self, flow: &mut dyn Flow) { + pub fn compute_floats_in(&mut self, flow: &mut Flow) { let base_flow = flow.base(); if base_flow.flags.contains(FlowFlags::CLEARS_LEFT) { self.left = Au(0) @@ -506,7 +506,7 @@ impl SpeculatedFloatPlacement { /// Given the speculated inline size of the floats out for this flow's last child, computes the /// speculated inline size of the floats out for this flow. - pub fn compute_floats_out(&mut self, flow: &mut dyn Flow) { + pub fn compute_floats_out(&mut self, flow: &mut Flow) { if flow.is_block_like() { let block_flow = flow.as_block(); if block_flow.formatting_context_type() != FormattingContextType::None { @@ -564,9 +564,7 @@ impl SpeculatedFloatPlacement { } /// Given a flow, computes the speculated inline size of the floats in of its first child. - pub fn compute_floats_in_for_first_child( - parent_flow: &mut dyn Flow, - ) -> SpeculatedFloatPlacement { + pub fn compute_floats_in_for_first_child(parent_flow: &mut Flow) -> SpeculatedFloatPlacement { if !parent_flow.is_block_like() { return parent_flow.base().speculated_float_placement_in; } diff --git a/components/layout/flow.rs b/components/layout/flow.rs index 4bf7622636c7..1b0781c527e1 100644 --- a/components/layout/flow.rs +++ b/components/layout/flow.rs @@ -26,36 +26,29 @@ //! similar methods. use app_units::Au; -use crate::block::{BlockFlow, FormattingContextType}; -use crate::context::LayoutContext; -use crate::display_list::items::ClippingAndScrolling; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; -use crate::flex::FlexFlow; -use crate::floats::{Floats, SpeculatedFloatPlacement}; -use crate::flow_list::{FlowList, FlowListIterator, MutFlowListIterator}; -use crate::flow_ref::{FlowRef, WeakFlowRef}; -use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::inline::InlineFlow; -use crate::model::{CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo}; -use crate::multicol::MulticolFlow; -use crate::parallel::FlowParallelInfo; -use crate::table::TableFlow; -use crate::table_caption::TableCaptionFlow; -use crate::table_cell::TableCellFlow; -use crate::table_colgroup::TableColGroupFlow; -use crate::table_row::TableRowFlow; -use crate::table_rowgroup::TableRowGroupFlow; -use crate::table_wrapper::TableWrapperFlow; -use euclid::{Point2D, Rect, Size2D, Vector2D}; -use gfx_traits::print_tree::PrintTree; +use block::{BlockFlow, FormattingContextType}; +use context::LayoutContext; +use display_list::{DisplayListBuildState, StackingContextCollectionState}; +use display_list::items::ClippingAndScrolling; +use euclid::{Point2D, Vector2D, Rect, Size2D}; +use flex::FlexFlow; +use floats::{Floats, SpeculatedFloatPlacement}; +use flow_list::{FlowList, FlowListIterator, MutFlowListIterator}; +use flow_ref::{FlowRef, WeakFlowRef}; +use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::StackingContextId; +use gfx_traits::print_tree::PrintTree; +use inline::InlineFlow; +use model::{CollapsibleMargins, IntrinsicISizes, MarginCollapseInfo}; +use multicol::MulticolFlow; +use parallel::FlowParallelInfo; use serde::ser::{Serialize, SerializeStruct, Serializer}; use servo_geometry::{au_rect_to_f32_rect, f32_rect_to_au_rect, MaxRect}; use std::fmt; use std::iter::Zip; use std::slice::IterMut; -use std::sync::atomic::Ordering; use std::sync::Arc; +use std::sync::atomic::Ordering; use style::computed_values::clear::T as Clear; use style::computed_values::float::T as Float; use style::computed_values::overflow_x::T as StyleOverflow; @@ -67,6 +60,13 @@ use style::properties::ComputedValues; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::computed::LengthOrPercentageOrAuto; +use table::TableFlow; +use table_caption::TableCaptionFlow; +use table_cell::TableCellFlow; +use table_colgroup::TableColGroupFlow; +use table_row::TableRowFlow; +use table_rowgroup::TableRowGroupFlow; +use table_wrapper::TableWrapperFlow; use webrender_api::LayoutTransform; /// This marker trait indicates that a type is a struct with `#[repr(C)]` whose first field @@ -255,7 +255,7 @@ pub trait Flow: HasBaseFlow + fmt::Debug + Sync + Send + 'static { &mut self, layout_context: &LayoutContext, _fragmentation_context: Option, - ) -> Option> { + ) -> Option> { fn recursive_assign_block_size( flow: &mut F, ctx: &LayoutContext, @@ -423,13 +423,13 @@ pub trait Flow: HasBaseFlow + fmt::Debug + Sync + Send + 'static { /// depth of the flow tree during fragment iteration. fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ); /// Mutably iterates through fragments in this flow. - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)); + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)); fn compute_collapsible_block_start_margin( &mut self, @@ -502,7 +502,7 @@ pub trait Flow: HasBaseFlow + fmt::Debug + Sync + Send + 'static { /// Attempts to perform incremental fixup of this flow by replacing its fragment's style with /// the new style. This can only succeed if the flow has exactly one fragment. - fn repair_style(&mut self, new_style: &crate::ServoArc); + fn repair_style(&mut self, new_style: &::ServoArc); /// Print any extra children (such as fragments) contained in this Flow /// for debugging purposes. Any items inserted into the tree will become @@ -578,7 +578,7 @@ pub trait ImmutableFlowUtils { pub trait MutableFlowUtils { /// Calls `repair_style` and `bubble_inline_sizes`. You should use this method instead of /// calling them individually, since there is no reason not to perform both operations. - fn repair_style_and_bubble_inline_sizes(self, style: &crate::ServoArc); + fn repair_style_and_bubble_inline_sizes(self, style: &::ServoArc); } pub trait MutableOwnedFlowUtils { @@ -813,8 +813,8 @@ pub struct AbsoluteDescendantIter<'a> { } impl<'a> Iterator for AbsoluteDescendantIter<'a> { - type Item = &'a mut dyn Flow; - fn next(&mut self) -> Option<&'a mut dyn Flow> { + type Item = &'a mut Flow; + fn next(&mut self) -> Option<&'a mut Flow> { self.iter .next() .map(|info| FlowRef::deref_mut(&mut info.flow)) @@ -1245,7 +1245,7 @@ impl BaseFlow { } } -impl<'a> ImmutableFlowUtils for &'a dyn Flow { +impl<'a> ImmutableFlowUtils for &'a Flow { /// Returns true if this flow is a block flow or subclass thereof. fn is_block_like(self) -> bool { self.class().is_block_like() @@ -1419,10 +1419,10 @@ impl<'a> ImmutableFlowUtils for &'a dyn Flow { } } -impl<'a> MutableFlowUtils for &'a mut dyn Flow { +impl<'a> MutableFlowUtils for &'a mut Flow { /// Calls `repair_style` and `bubble_inline_sizes`. You should use this method instead of /// calling them individually, since there is no reason not to perform both operations. - fn repair_style_and_bubble_inline_sizes(self, style: &crate::ServoArc) { + fn repair_style_and_bubble_inline_sizes(self, style: &::ServoArc) { self.repair_style(style); self.mut_base().update_flags_if_needed(style); self.bubble_inline_sizes(); @@ -1550,8 +1550,8 @@ impl ContainingBlockLink { pub struct OpaqueFlow(pub usize); impl OpaqueFlow { - pub fn from_flow(flow: &dyn Flow) -> OpaqueFlow { - let object_ptr: *const dyn Flow = flow; + pub fn from_flow(flow: &Flow) -> OpaqueFlow { + let object_ptr: *const Flow = flow; let data_ptr = object_ptr as *const (); OpaqueFlow(data_ptr as usize) } diff --git a/components/layout/flow_list.rs b/components/layout/flow_list.rs index 07b42f19a9db..53ec0d8912ae 100644 --- a/components/layout/flow_list.rs +++ b/components/layout/flow_list.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::flow::{Flow, FlowClass}; -use crate::flow_ref::FlowRef; +use flow::{Flow, FlowClass}; +use flow_ref::FlowRef; use serde::ser::{Serialize, SerializeSeq, Serializer}; -use serde_json::{to_value, Map, Value}; -use std::collections::{linked_list, LinkedList}; +use serde_json::{Map, Value, to_value}; +use std::collections::{LinkedList, linked_list}; use std::ops::Deref; use std::sync::Arc; @@ -69,11 +69,11 @@ impl FlowList { self.flows.push_back(new_tail); } - pub fn push_back_arc(&mut self, new_head: Arc) { + pub fn push_back_arc(&mut self, new_head: Arc) { self.flows.push_back(FlowRef::new(new_head)); } - pub fn back(&self) -> Option<&dyn Flow> { + pub fn back(&self) -> Option<&Flow> { self.flows.back().map(|x| &**x) } @@ -84,15 +84,15 @@ impl FlowList { self.flows.push_front(new_head); } - pub fn push_front_arc(&mut self, new_head: Arc) { + pub fn push_front_arc(&mut self, new_head: Arc) { self.flows.push_front(FlowRef::new(new_head)); } - pub fn pop_front_arc(&mut self) -> Option> { + pub fn pop_front_arc(&mut self) -> Option> { self.flows.pop_front().map(FlowRef::into_arc) } - pub fn front(&self) -> Option<&dyn Flow> { + pub fn front(&self) -> Option<&Flow> { self.flows.front().map(|x| &**x) } @@ -161,21 +161,21 @@ impl FlowList { } impl<'a> DoubleEndedIterator for FlowListIterator<'a> { - fn next_back(&mut self) -> Option<&'a dyn Flow> { + fn next_back(&mut self) -> Option<&'a Flow> { self.it.next_back().map(Deref::deref) } } impl<'a> DoubleEndedIterator for MutFlowListIterator<'a> { - fn next_back(&mut self) -> Option<&'a mut dyn Flow> { + fn next_back(&mut self) -> Option<&'a mut Flow> { self.it.next_back().map(FlowRef::deref_mut) } } impl<'a> Iterator for FlowListIterator<'a> { - type Item = &'a dyn Flow; + type Item = &'a Flow; #[inline] - fn next(&mut self) -> Option<&'a dyn Flow> { + fn next(&mut self) -> Option<&'a Flow> { self.it.next().map(Deref::deref) } @@ -186,9 +186,9 @@ impl<'a> Iterator for FlowListIterator<'a> { } impl<'a> Iterator for MutFlowListIterator<'a> { - type Item = &'a mut dyn Flow; + type Item = &'a mut Flow; #[inline] - fn next(&mut self) -> Option<&'a mut dyn Flow> { + fn next(&mut self) -> Option<&'a mut Flow> { self.it.next().map(FlowRef::deref_mut) } @@ -206,7 +206,7 @@ pub struct FlowListRandomAccessMut<'a> { } impl<'a> FlowListRandomAccessMut<'a> { - pub fn get<'b>(&'b mut self, index: usize) -> &'b mut dyn Flow { + pub fn get<'b>(&'b mut self, index: usize) -> &'b mut Flow { while index >= self.cache.len() { match self.iterator.next() { None => panic!("Flow index out of range!"), diff --git a/components/layout/flow_ref.rs b/components/layout/flow_ref.rs index 6b9027459ee5..b2da85b74aca 100644 --- a/components/layout/flow_ref.rs +++ b/components/layout/flow_ref.rs @@ -8,16 +8,16 @@ //! be superfluous. This design is largely duplicating logic of Arc and //! Weak; please see comments there for details. -use crate::flow::Flow; +use flow::Flow; use std::ops::Deref; use std::sync::{Arc, Weak}; #[derive(Clone, Debug)] -pub struct FlowRef(Arc); +pub struct FlowRef(Arc); impl Deref for FlowRef { - type Target = dyn Flow; - fn deref(&self) -> &dyn Flow { + type Target = Flow; + fn deref(&self) -> &Flow { self.0.deref() } } @@ -25,19 +25,19 @@ impl Deref for FlowRef { impl FlowRef { /// `FlowRef`s can only be made available to the traversal code. /// See https://github.com/servo/servo/issues/14014 for more details. - pub fn new(mut r: Arc) -> Self { + pub fn new(mut r: Arc) -> Self { // This assertion checks that this `FlowRef` does not alias normal `Arc`s. // If that happens, we're in trouble. assert!(Arc::get_mut(&mut r).is_some()); FlowRef(r) } - pub fn get_mut(this: &mut FlowRef) -> Option<&mut dyn Flow> { + pub fn get_mut(this: &mut FlowRef) -> Option<&mut Flow> { Arc::get_mut(&mut this.0) } pub fn downgrade(this: &FlowRef) -> WeakFlowRef { WeakFlowRef(Arc::downgrade(&this.0)) } - pub fn into_arc(mut this: FlowRef) -> Arc { + pub fn into_arc(mut this: FlowRef) -> Arc { // This assertion checks that this `FlowRef` does not alias normal `Arc`s. // If that happens, we're in trouble. assert!(FlowRef::get_mut(&mut this).is_some()); @@ -48,14 +48,14 @@ impl FlowRef { /// See https://github.com/servo/servo/issues/6503 /// Use Arc::get_mut instead when possible (e.g. on an Arc that was just created). #[allow(unsafe_code)] - pub fn deref_mut(this: &mut FlowRef) -> &mut dyn Flow { - let ptr: *const dyn Flow = &*this.0; - unsafe { &mut *(ptr as *mut dyn Flow) } + pub fn deref_mut(this: &mut FlowRef) -> &mut Flow { + let ptr: *const Flow = &*this.0; + unsafe { &mut *(ptr as *mut Flow) } } } #[derive(Clone, Debug)] -pub struct WeakFlowRef(Weak); +pub struct WeakFlowRef(Weak); impl WeakFlowRef { pub fn upgrade(&self) -> Option { diff --git a/components/layout/fragment.rs b/components/layout/fragment.rs index b896f1df8bfa..65fd277fdde8 100644 --- a/components/layout/fragment.rs +++ b/components/layout/fragment.rs @@ -4,44 +4,43 @@ //! The `Fragment` type, which represents the leaves of the layout tree. +#![deny(unsafe_code)] + +use ServoArc; use app_units::Au; -use canvas_traits::canvas::{CanvasId, CanvasMsg}; -use crate::context::{with_thread_local_font_context, LayoutContext}; -use crate::display_list::items::{ClipScrollNodeIndex, OpaqueNode, BLUR_INFLATION_FACTOR}; -use crate::display_list::ToLayout; -use crate::floats::ClearType; -use crate::flow::{GetBaseFlow, ImmutableFlowUtils}; -use crate::flow_ref::FlowRef; -use crate::inline::{InlineFragmentContext, InlineFragmentNodeFlags, InlineFragmentNodeInfo}; -use crate::inline::{InlineMetrics, LineMetrics}; -#[cfg(debug_assertions)] -use crate::layout_debug; -use crate::model::style_length; -use crate::model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, SizeConstraint}; -use crate::text; -use crate::text::TextRunScanner; -use crate::wrapper::ThreadSafeLayoutNodeHelpers; -use crate::ServoArc; -use euclid::{Point2D, Rect, Size2D, Vector2D}; +use canvas_traits::canvas::{CanvasMsg, CanvasId}; +use context::{LayoutContext, with_thread_local_font_context}; +use display_list::ToLayout; +use display_list::items::{BLUR_INFLATION_FACTOR, ClipScrollNodeIndex, OpaqueNode}; +use euclid::{Point2D, Vector2D, Rect, Size2D}; +use floats::ClearType; +use flow::{GetBaseFlow, ImmutableFlowUtils}; +use flow_ref::FlowRef; +use gfx; use gfx::text::glyph::ByteIndex; use gfx::text::text_run::{TextRun, TextRunSlice}; use gfx_traits::StackingContextId; +use inline::{InlineFragmentNodeFlags, InlineFragmentContext, InlineFragmentNodeInfo}; +use inline::{InlineMetrics, LineMetrics}; use ipc_channel::ipc::IpcSender; +#[cfg(debug_assertions)] +use layout_debug; +use model::{self, IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto, SizeConstraint}; +use model::style_length; use msg::constellation_msg::{BrowsingContextId, PipelineId}; use net_traits::image::base::{Image, ImageMetadata}; use net_traits::image_cache::{ImageOrMetadataAvailable, UsePlaceholder}; use range::*; -use script_layout_interface::wrapper_traits::{ - PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, -}; -use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource, HTMLMediaData, SVGSVGData}; +use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; +use script_layout_interface::SVGSVGData; +use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use serde::ser::{Serialize, SerializeStruct, Serializer}; use servo_url::ServoUrl; +use std::{f32, fmt}; use std::borrow::ToOwned; -use std::cmp::{max, min, Ordering}; +use std::cmp::{Ordering, max, min}; use std::collections::LinkedList; use std::sync::{Arc, Mutex}; -use std::{f32, fmt}; use style::computed_values::border_collapse::T as BorderCollapse; use style::computed_values::box_sizing::T as BoxSizing; use style::computed_values::clear::T as Clear; @@ -60,11 +59,14 @@ use style::properties::ComputedValues; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; use style::str::char_is_whitespace; -use style::values::computed::counters::ContentItem; use style::values::computed::{Length, LengthOrPercentage, LengthOrPercentageOrAuto}; +use style::values::computed::counters::ContentItem; use style::values::generics::box_::{Perspective, VerticalAlign}; use style::values::generics::transform; +use text; +use text::TextRunScanner; use webrender_api::{self, LayoutTransform}; +use wrapper::ThreadSafeLayoutNodeHelpers; // From gfxFontConstants.h in Firefox. static FONT_SUBSCRIPT_OFFSET_RATIO: f32 = 0.20; @@ -180,7 +182,6 @@ pub enum SpecificFragmentInfo { Iframe(IframeFragmentInfo), Image(Box), - Media(Box), Canvas(Box), Svg(Box), @@ -218,7 +219,6 @@ impl SpecificFragmentInfo { SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::Svg(_) | SpecificFragmentInfo::Table | @@ -242,7 +242,6 @@ impl SpecificFragmentInfo { pub fn get_type(&self) -> &'static str { match *self { SpecificFragmentInfo::Canvas(_) => "SpecificFragmentInfo::Canvas", - SpecificFragmentInfo::Media(_) => "SpecificFragmentInfo::Media", SpecificFragmentInfo::Generic => "SpecificFragmentInfo::Generic", SpecificFragmentInfo::GeneratedContent(_) => "SpecificFragmentInfo::GeneratedContent", SpecificFragmentInfo::Iframe(_) => "SpecificFragmentInfo::Iframe", @@ -365,19 +364,6 @@ impl CanvasFragmentInfo { } } -#[derive(Clone)] -pub struct MediaFragmentInfo { - pub current_frame: Option<(webrender_api::ImageKey, i32, i32)>, -} - -impl MediaFragmentInfo { - pub fn new(data: HTMLMediaData) -> MediaFragmentInfo { - MediaFragmentInfo { - current_frame: data.current_frame, - } - } -} - #[derive(Clone)] pub struct SvgFragmentInfo { pub dom_width: Au, @@ -400,11 +386,6 @@ pub struct ImageFragmentInfo { pub metadata: Option, } -enum ImageOrMetadata { - Image(Arc), - Metadata(ImageMetadata), -} - impl ImageFragmentInfo { /// Creates a new image fragment from the given URL and local image cache. /// @@ -416,34 +397,14 @@ impl ImageFragmentInfo { node: &N, layout_context: &LayoutContext, ) -> ImageFragmentInfo { - // First use any image data present in the element... - let image_or_metadata = node - .image_data() - .and_then(|(image, metadata)| match (image, metadata) { - (Some(image), _) => Some(ImageOrMetadata::Image(image)), - (None, Some(metadata)) => Some(ImageOrMetadata::Metadata(metadata)), - _ => None, - }) - .or_else(|| { - url.and_then(|url| { - // Otherwise query the image cache for anything known about the associated source URL. - layout_context - .get_or_request_image_or_meta(node.opaque(), url, UsePlaceholder::Yes) - .map(|result| match result { - ImageOrMetadataAvailable::ImageAvailable(i, _) => { - ImageOrMetadata::Image(i) - }, - ImageOrMetadataAvailable::MetadataAvailable(m) => { - ImageOrMetadata::Metadata(m) - }, - }) - }) - }); + let image_or_metadata = url.and_then(|url| { + layout_context.get_or_request_image_or_meta(node.opaque(), url, UsePlaceholder::Yes) + }); let current_pixel_density = density.unwrap_or(1f64); let (image, metadata) = match image_or_metadata { - Some(ImageOrMetadata::Image(i)) => { + Some(ImageOrMetadataAvailable::ImageAvailable(i, _)) => { let height = (i.height as f64 / current_pixel_density) as u32; let width = (i.width as f64 / current_pixel_density) as u32; ( @@ -458,13 +419,15 @@ impl ImageFragmentInfo { }), ) }, - Some(ImageOrMetadata::Metadata(m)) => ( - None, - Some(ImageMetadata { - height: (m.height as f64 / current_pixel_density) as u32, - width: (m.width as f64 / current_pixel_density) as u32, - }), - ), + Some(ImageOrMetadataAvailable::MetadataAvailable(m)) => { + ( + None, + Some(ImageMetadata { + height: (m.height as f64 / current_pixel_density) as u32, + width: (m.width as f64 / current_pixel_density) as u32, + }), + ) + }, None => (None, None), }; @@ -871,7 +834,6 @@ impl Fragment { ) -> QuantitiesIncludedInIntrinsicInlineSizes { match self.specific { SpecificFragmentInfo::Canvas(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | @@ -1017,13 +979,6 @@ impl Fragment { Au(0) } }, - SpecificFragmentInfo::Media(ref info) => { - if let Some((_, width, _)) = info.current_frame { - Au::from_px(width as i32) - } else { - Au(0) - } - }, SpecificFragmentInfo::Canvas(ref info) => info.dom_width, SpecificFragmentInfo::Svg(ref info) => info.dom_width, // Note: Currently for replaced element with no intrinsic size, @@ -1047,13 +1002,6 @@ impl Fragment { Au(0) } }, - SpecificFragmentInfo::Media(ref info) => { - if let Some((_, _, height)) = info.current_frame { - Au::from_px(height as i32) - } else { - Au(0) - } - }, SpecificFragmentInfo::Canvas(ref info) => info.dom_height, SpecificFragmentInfo::Svg(ref info) => info.dom_height, SpecificFragmentInfo::Iframe(_) => Au::from_px(DEFAULT_REPLACED_HEIGHT), @@ -1066,7 +1014,6 @@ impl Fragment { match self.specific { SpecificFragmentInfo::Image(_) | SpecificFragmentInfo::Canvas(_) | - SpecificFragmentInfo::Media(_) | // TODO(stshine): According to the SVG spec, whether a SVG element has intrinsic // aspect ratio is determined by the `preserveAspectRatio` attribute. Since for // now SVG is far from implemented, we simply choose the default behavior that @@ -1178,21 +1125,17 @@ impl Fragment { (_, Ordering::Equal) => (first_isize, first_bsize), // When both rectangles grow (smaller than min sizes), // Choose the larger one; - (Ordering::Greater, Ordering::Greater) => { - if first_isize > second_isize { - (first_isize, first_bsize) - } else { - (second_isize, second_bsize) - } + (Ordering::Greater, Ordering::Greater) => if first_isize > second_isize { + (first_isize, first_bsize) + } else { + (second_isize, second_bsize) }, // When both rectangles shrink (larger than max sizes), // Choose the smaller one; - (Ordering::Less, Ordering::Less) => { - if first_isize > second_isize { - (second_isize, second_bsize) - } else { - (first_isize, first_bsize) - } + (Ordering::Less, Ordering::Less) => if first_isize > second_isize { + (second_isize, second_bsize) + } else { + (first_isize, first_bsize) }, // It does not matter which we choose here, because both sizes // will be clamped to constraint; @@ -1606,7 +1549,6 @@ impl Fragment { result.union_block(&block_flow.base.intrinsic_inline_sizes) }, SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Svg(_) => { @@ -2082,7 +2024,6 @@ impl Fragment { }, SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | @@ -2174,7 +2115,6 @@ impl Fragment { SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::InlineBlock(_) | SpecificFragmentInfo::InlineAbsoluteHypothetical(_) | SpecificFragmentInfo::InlineAbsolute(_) | @@ -2231,7 +2171,6 @@ impl Fragment { SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::Svg(_) => true, _ => false, } @@ -2263,7 +2202,6 @@ impl Fragment { SpecificFragmentInfo::Canvas(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::Svg(_) | SpecificFragmentInfo::Generic | SpecificFragmentInfo::GeneratedContent(_) => { @@ -2592,7 +2530,6 @@ impl Fragment { SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::Svg(_) | SpecificFragmentInfo::Table | @@ -3120,7 +3057,6 @@ impl Fragment { SpecificFragmentInfo::GeneratedContent(_) | SpecificFragmentInfo::Iframe(_) | SpecificFragmentInfo::Image(_) | - SpecificFragmentInfo::Media(_) | SpecificFragmentInfo::ScannedText(_) | SpecificFragmentInfo::TruncatedFragment(_) | SpecificFragmentInfo::Svg(_) | @@ -3181,8 +3117,7 @@ impl Fragment { perspective_origin .vertical .to_used_value(stacking_relative_border_box.size.height), - ) - .to_layout(); + ).to_layout(); let pre_transform = LayoutTransform::create_translation( perspective_origin.x, diff --git a/components/layout/generated_content.rs b/components/layout/generated_content.rs index 8d1befdde335..90341abe3d94 100644 --- a/components/layout/generated_content.rs +++ b/components/layout/generated_content.rs @@ -8,14 +8,10 @@ //! done in parallel and is therefore a sequential pass that runs on as little of the flow tree //! as possible. -use crate::context::{with_thread_local_font_context, LayoutContext}; -use crate::display_list::items::OpaqueNode; -use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; -use crate::fragment::{ - Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo, -}; -use crate::text::TextRunScanner; -use crate::traversal::InorderFlowTraversal; +use context::{LayoutContext, with_thread_local_font_context}; +use display_list::items::OpaqueNode; +use flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; +use fragment::{Fragment, GeneratedContentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; use script_layout_interface::wrapper_traits::PseudoElementType; use smallvec::SmallVec; use std::collections::{HashMap, LinkedList}; @@ -25,6 +21,8 @@ use style::properties::ComputedValues; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; use style::values::generics::counters::ContentItem; +use text::TextRunScanner; +use traversal::InorderFlowTraversal; // Decimal styles per CSS-COUNTER-STYLES § 6.1: static DECIMAL: [char; 10] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; @@ -152,7 +150,7 @@ impl<'a> ResolveGeneratedContent<'a> { impl<'a> InorderFlowTraversal for ResolveGeneratedContent<'a> { #[inline] - fn process(&mut self, flow: &mut dyn Flow, level: u32) { + fn process(&mut self, flow: &mut Flow, level: u32) { let mut mutator = ResolveGeneratedContentFragmentMutator { traversal: self, level: level, @@ -163,7 +161,7 @@ impl<'a> InorderFlowTraversal for ResolveGeneratedContent<'a> { } #[inline] - fn should_process_subtree(&mut self, flow: &mut dyn Flow) -> bool { + fn should_process_subtree(&mut self, flow: &mut Flow) -> bool { flow.base() .restyle_damage .intersects(ServoRestyleDamage::RESOLVE_GENERATED_CONTENT) || @@ -366,15 +364,16 @@ impl<'a, 'b> ResolveGeneratedContentFragmentMutator<'a, 'b> { if quotes.0.is_empty() { return String::new(); } - let pair = if self.traversal.quote as usize >= quotes.0.len() { + let &(ref open_quote, ref close_quote) = if self.traversal.quote as usize >= quotes.0.len() + { quotes.0.last().unwrap() } else { "es.0[self.traversal.quote as usize] }; if close { - pair.closing.to_string() + close_quote.to_string() } else { - pair.opening.to_string() + open_quote.to_string() } } } @@ -429,7 +428,7 @@ impl Counter { layout_context: &LayoutContext, node: OpaqueNode, pseudo: PseudoElementType, - style: crate::ServoArc, + style: ::ServoArc, list_style_type: ListStyleType, mode: RenderingMode, ) -> Option { @@ -493,7 +492,7 @@ fn render_text( layout_context: &LayoutContext, node: OpaqueNode, pseudo: PseudoElementType, - style: crate::ServoArc, + style: ::ServoArc, string: String, ) -> Option { let mut fragments = LinkedList::new(); diff --git a/components/layout/incremental.rs b/components/layout/incremental.rs index 7dde93384b77..f0f76453919f 100644 --- a/components/layout/incremental.rs +++ b/components/layout/incremental.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::flow::{Flow, FlowFlags, GetBaseFlow}; +use flow::{FlowFlags, Flow, GetBaseFlow}; use style::computed_values::float::T as Float; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; @@ -27,7 +27,7 @@ pub trait LayoutDamageComputation { fn reflow_entire_document(self); } -impl<'a> LayoutDamageComputation for &'a mut dyn Flow { +impl<'a> LayoutDamageComputation for &'a mut Flow { fn compute_layout_damage(self) -> SpecialRestyleDamage { let mut special_damage = SpecialRestyleDamage::empty(); let is_absolutely_positioned = self @@ -53,7 +53,7 @@ impl<'a> LayoutDamageComputation for &'a mut dyn Flow { .damage_for_child(is_absolutely_positioned, child_is_absolutely_positioned), ); { - let kid: &mut dyn Flow = kid; + let kid: &mut Flow = kid; special_damage.insert(kid.compute_layout_damage()); } self_base.restyle_damage.insert( diff --git a/components/layout/inline.rs b/components/layout/inline.rs index 080c68129a28..7a66ad84bacb 100644 --- a/components/layout/inline.rs +++ b/components/layout/inline.rs @@ -2,33 +2,33 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +#![deny(unsafe_code)] + +use ServoArc; use app_units::{Au, MIN_AU}; -use crate::block::AbsoluteAssignBSizesTraversal; -use crate::context::{LayoutContext, LayoutFontContext}; -use crate::display_list::items::OpaqueNode; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::{DisplayListBuildState, InlineFlowDisplayListBuilding}; -use crate::floats::{FloatKind, Floats, PlacementInfo}; -use crate::flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag}; -use crate::flow::{EarlyAbsolutePositionInfo, FlowFlags, GetBaseFlow, OpaqueFlow}; -use crate::flow_ref::FlowRef; -use crate::fragment::FragmentFlags; -use crate::fragment::SpecificFragmentInfo; -use crate::fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::model::IntrinsicISizesContribution; -use crate::text; -use crate::traversal::PreorderFlowTraversal; -use crate::ServoArc; +use block::AbsoluteAssignBSizesTraversal; +use context::{LayoutContext, LayoutFontContext}; +use display_list::{DisplayListBuildState, InlineFlowDisplayListBuilding}; +use display_list::StackingContextCollectionState; +use display_list::items::OpaqueNode; use euclid::{Point2D, Size2D}; +use floats::{FloatKind, Floats, PlacementInfo}; +use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag}; +use flow::{FlowFlags, EarlyAbsolutePositionInfo, GetBaseFlow, OpaqueFlow}; +use flow_ref::FlowRef; +use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, Overflow}; +use fragment::FragmentFlags; +use fragment::SpecificFragmentInfo; use gfx::font::FontMetrics; use gfx_traits::print_tree::PrintTree; +use layout_debug; +use model::IntrinsicISizesContribution; use range::{Range, RangeIndex}; use script_layout_interface::wrapper_traits::PseudoElementType; +use std::{fmt, i32, isize, mem}; use std::cmp::max; use std::collections::VecDeque; use std::sync::Arc; -use std::{fmt, i32, isize, mem}; use style::computed_values::display::T as Display; use style::computed_values::overflow_x::T as StyleOverflow; use style::computed_values::position::T as Position; @@ -41,6 +41,8 @@ use style::servo::restyle_damage::ServoRestyleDamage; use style::values::computed::box_::VerticalAlign; use style::values::generics::box_::VerticalAlign as GenericVerticalAlign; use style::values::specified::text::TextOverflowSide; +use text; +use traversal::PreorderFlowTraversal; use unicode_bidi as bidi; /// `Line`s are represented as offsets into the child list, rather than @@ -316,8 +318,7 @@ impl LineBreaker { .map(|fragment| match fragment.specific { SpecificFragmentInfo::ScannedText(ref info) => info.run.bidi_level, _ => para_level, - }) - .collect(); + }).collect(); let mut lines = mem::replace(&mut self.lines, Vec::new()); @@ -337,8 +338,7 @@ impl LineBreaker { let start = FragmentIndex(run.start as isize); let len = FragmentIndex(run.len() as isize); (Range::new(start, len), levels[run.start]) - }) - .collect(), + }).collect(), ); } } @@ -945,7 +945,7 @@ impl InlineFragments { } #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for InlineFlow {} +unsafe impl ::flow::HasBaseFlow for InlineFlow {} /// Flows for inline layout. #[derive(Serialize)] @@ -1721,8 +1721,7 @@ impl Flow for InlineFlow { debug_assert!(first_fragment_index < self.fragments.fragments.len()); let first_fragment = &self.fragments.fragments[first_fragment_index]; let padding_box_origin = (first_fragment.border_box - - first_fragment.style.logical_border_width()) - .start; + first_fragment.style.logical_border_width()).start; containing_block_positions.push( padding_box_origin.to_physical(self.base.writing_mode, container_size), ); @@ -1736,8 +1735,7 @@ impl Flow for InlineFlow { debug_assert!(first_fragment_index < self.fragments.fragments.len()); let first_fragment = &self.fragments.fragments[first_fragment_index]; let padding_box_origin = (first_fragment.border_box - - first_fragment.style.logical_border_width()) - .start; + first_fragment.style.logical_border_width()).start; containing_block_positions.push( padding_box_origin.to_physical(self.base.writing_mode, container_size), ); @@ -1854,7 +1852,7 @@ impl Flow for InlineFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -1882,13 +1880,12 @@ impl Flow for InlineFlow { relative_containing_block_size, relative_containing_block_mode, CoordinateSystem::Own, - ) - .translate(&stacking_context_position.to_vector()), + ).translate(&stacking_context_position.to_vector()), ) } } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { for fragment in &mut self.fragments.fragments { (*mutator)(fragment) } diff --git a/components/layout/layout_debug.rs b/components/layout/layout_debug.rs index dec9d49def54..70b73d9b6fd6 100644 --- a/components/layout/layout_debug.rs +++ b/components/layout/layout_debug.rs @@ -5,15 +5,15 @@ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to make layout debugging easier. -use crate::flow::GetBaseFlow; -use crate::flow_ref::FlowRef; +use flow::GetBaseFlow; +use flow_ref::FlowRef; use serde_json::{to_string, to_value, Value}; use std::borrow::ToOwned; use std::cell::RefCell; use std::fs::File; use std::io::Write; #[cfg(debug_assertions)] -use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; +use std::sync::atomic::{ATOMIC_USIZE_INIT, AtomicUsize, Ordering}; thread_local!(static STATE_KEY: RefCell> = RefCell::new(None)); diff --git a/components/layout/lib.rs b/components/layout/lib.rs index 2bf13e32173a..3dc289a11fa9 100644 --- a/components/layout/lib.rs +++ b/components/layout/lib.rs @@ -4,16 +4,49 @@ #![deny(unsafe_code)] +extern crate app_units; +extern crate atomic_refcell; #[macro_use] extern crate bitflags; +extern crate canvas_traits; +extern crate euclid; +extern crate fnv; +extern crate fxhash; +extern crate gfx; +extern crate gfx_traits; #[macro_use] extern crate html5ever; +extern crate ipc_channel; +extern crate libc; #[macro_use] extern crate log; +extern crate malloc_size_of; +extern crate msg; +extern crate net_traits; +extern crate ordered_float; +extern crate parking_lot; +extern crate profile_traits; #[macro_use] extern crate range; +extern crate rayon; +extern crate script_layout_interface; +extern crate script_traits; #[macro_use] extern crate serde; +extern crate serde_json; +extern crate servo_arc; +extern crate servo_atoms; +extern crate servo_channel; +extern crate servo_config; +extern crate servo_geometry; +extern crate servo_url; +extern crate smallvec; +extern crate style; +extern crate style_traits; +extern crate unicode_bidi; +extern crate unicode_script; +extern crate webrender_api; +extern crate xi_unicode; #[macro_use] pub mod layout_debug; @@ -54,9 +87,9 @@ pub mod traversal; pub mod wrapper; // For unit tests: +pub use fragment::Fragment; +pub use fragment::SpecificFragmentInfo; pub use self::data::LayoutData; -pub use crate::fragment::Fragment; -pub use crate::fragment::SpecificFragmentInfo; // We can't use servo_arc for everything in layout, because the Flow stuff uses // weak references. diff --git a/components/layout/list_item.rs b/components/layout/list_item.rs index 893b63fb66ac..72e87578635b 100644 --- a/components/layout/list_item.rs +++ b/components/layout/list_item.rs @@ -5,20 +5,20 @@ //! Layout for elements with a CSS `display` property of `list-item`. These elements consist of a //! block and an extra inline fragment for the marker. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::BlockFlow; -use crate::context::{with_thread_local_font_context, LayoutContext}; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::{DisplayListBuildState, ListItemFlowDisplayListBuilding}; -use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, OpaqueFlow}; -use crate::fragment::Overflow; -use crate::fragment::{ - CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo, -}; -use crate::generated_content; -use crate::inline::InlineFlow; +use block::BlockFlow; +use context::{LayoutContext, with_thread_local_font_context}; +use display_list::{DisplayListBuildState, ListItemFlowDisplayListBuilding}; +use display_list::StackingContextCollectionState; use euclid::Point2D; +use floats::FloatKind; +use flow::{Flow, FlowClass, OpaqueFlow}; +use fragment::{CoordinateSystem, Fragment, FragmentBorderBoxIterator, GeneratedContentInfo}; +use fragment::Overflow; +use generated_content; +use inline::InlineFlow; use style::computed_values::list_style_type::T as ListStyleType; use style::computed_values::position::T as Position; use style::logical_geometry::LogicalSize; @@ -26,7 +26,7 @@ use style::properties::ComputedValues; use style::servo::restyle_damage::ServoRestyleDamage; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for ListItemFlow {} +unsafe impl ::flow::HasBaseFlow for ListItemFlow {} /// A block with the CSS `display` property equal to `list-item`. #[derive(Debug)] @@ -196,7 +196,7 @@ impl Flow for ListItemFlow { self.block_flow.collect_stacking_contexts(state); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -231,7 +231,7 @@ impl Flow for ListItemFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -259,14 +259,13 @@ impl Flow for ListItemFlow { .early_absolute_position_info .relative_containing_block_mode, CoordinateSystem::Own, - ) - .translate(&stacking_context_position.to_vector()), + ).translate(&stacking_context_position.to_vector()), ); } } } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator); for marker in &mut self.marker_fragments { diff --git a/components/layout/model.rs b/components/layout/model.rs index 3fba3e27fba6..50959398f27c 100644 --- a/components/layout/model.rs +++ b/components/layout/model.rs @@ -4,15 +4,17 @@ //! Borders, padding, and margins. +#![deny(unsafe_code)] + use app_units::Au; -use crate::fragment::Fragment; -use euclid::SideOffsets2D; +use euclid::{SideOffsets2D, Size2D}; +use fragment::Fragment; use std::cmp::{max, min}; use std::fmt; use style::logical_geometry::{LogicalMargin, WritingMode}; use style::properties::ComputedValues; -use style::values::computed::LengthOrPercentageOrNone; -use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrAuto}; +use style::values::computed::{BorderCornerRadius, LengthOrPercentageOrAuto}; +use style::values::computed::{LengthOrPercentage, LengthOrPercentageOrNone}; /// A collapsible margin. See CSS 2.1 § 8.3.1. #[derive(Clone, Copy, Debug)] @@ -505,16 +507,31 @@ pub fn style_length( ) -> MaybeAuto { match container_size { Some(length) => MaybeAuto::from_style(style_length, length), - None => { - if let LengthOrPercentageOrAuto::Length(length) = style_length { - MaybeAuto::Specified(Au::from(length)) - } else { - MaybeAuto::Auto - } + None => if let LengthOrPercentageOrAuto::Length(length) = style_length { + MaybeAuto::Specified(Au::from(length)) + } else { + MaybeAuto::Auto }, } } +/// Computes a border radius size against the containing size. +/// +/// Note that percentages in `border-radius` are resolved against the relevant +/// box dimension instead of only against the width per [1]: +/// +/// > Percentages: Refer to corresponding dimension of the border box. +/// +/// [1]: https://drafts.csswg.org/css-backgrounds-3/#border-radius +pub fn specified_border_radius( + radius: BorderCornerRadius, + containing_size: Size2D, +) -> Size2D { + let w = radius.0.width().to_used_value(containing_size.width); + let h = radius.0.height().to_used_value(containing_size.height); + Size2D::new(w, h) +} + #[inline] pub fn padding_from_style( style: &ComputedValues, @@ -582,23 +599,19 @@ impl SizeConstraint { ) -> SizeConstraint { let mut min_size = match container_size { Some(container_size) => min_size.to_used_value(container_size), - None => { - if let LengthOrPercentage::Length(length) = min_size { - Au::from(length) - } else { - Au(0) - } + None => if let LengthOrPercentage::Length(length) = min_size { + Au::from(length) + } else { + Au(0) }, }; let mut max_size = match container_size { Some(container_size) => max_size.to_used_value(container_size), - None => { - if let LengthOrPercentageOrNone::Length(length) = max_size { - Some(Au::from(length)) - } else { - None - } + None => if let LengthOrPercentageOrNone::Length(length) = max_size { + Some(Au::from(length)) + } else { + None }, }; // Make sure max size is not smaller than min size. diff --git a/components/layout/multicol.rs b/components/layout/multicol.rs index 0d2a72a7b3b3..082fa1a13670 100644 --- a/components/layout/multicol.rs +++ b/components/layout/multicol.rs @@ -4,27 +4,29 @@ //! CSS Multi-column layout http://dev.w3.org/csswg/css-multicol/ +#![deny(unsafe_code)] + +use ServoArc; use app_units::Au; -use crate::block::BlockFlow; -use crate::context::LayoutContext; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; -use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, FragmentationContext, GetBaseFlow, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::ServoArc; +use block::BlockFlow; +use context::LayoutContext; +use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::{Point2D, Vector2D}; +use floats::FloatKind; +use flow::{Flow, FlowClass, OpaqueFlow, FragmentationContext, GetBaseFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; -use std::cmp::{max, min}; +use std::cmp::{min, max}; use std::fmt; use std::sync::Arc; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; +use style::values::Either; use style::values::computed::{LengthOrPercentageOrAuto, LengthOrPercentageOrNone}; use style::values::generics::column::ColumnCount; -use style::values::Either; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for MulticolFlow {} +unsafe impl ::flow::HasBaseFlow for MulticolFlow {} #[repr(C)] pub struct MulticolFlow { @@ -36,7 +38,7 @@ pub struct MulticolFlow { } #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for MulticolColumnFlow {} +unsafe impl ::flow::HasBaseFlow for MulticolColumnFlow {} #[repr(C)] pub struct MulticolColumnFlow { @@ -164,8 +166,7 @@ impl Flow for MulticolFlow { LogicalSize::from_physical( self.block_flow.base.writing_mode, ctx.shared_context().viewport_size(), - ) - .block + ).block } }, }); @@ -241,7 +242,7 @@ impl Flow for MulticolFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -252,7 +253,7 @@ impl Flow for MulticolFlow { ); } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator); } @@ -295,7 +296,7 @@ impl Flow for MulticolColumnFlow { &mut self, layout_context: &LayoutContext, fragmentation_context: Option, - ) -> Option> { + ) -> Option> { Flow::fragment(&mut self.block_flow, layout_context, fragmentation_context) } @@ -345,7 +346,7 @@ impl Flow for MulticolColumnFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -356,7 +357,7 @@ impl Flow for MulticolColumnFlow { ); } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator); } diff --git a/components/layout/opaque_node.rs b/components/layout/opaque_node.rs index e516ff811fc6..400fd9692c5e 100644 --- a/components/layout/opaque_node.rs +++ b/components/layout/opaque_node.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::display_list::items::OpaqueNode; +use display_list::items::OpaqueNode; use libc::c_void; use script_traits::UntrustedNodeAddress; diff --git a/components/layout/parallel.rs b/components/layout/parallel.rs index 112623002ac6..d8f46a0f83cc 100644 --- a/components/layout/parallel.rs +++ b/components/layout/parallel.rs @@ -8,18 +8,19 @@ #![allow(unsafe_code)] -use crate::block::BlockFlow; -use crate::context::LayoutContext; -use crate::flow::{Flow, GetBaseFlow}; -use crate::flow_ref::FlowRef; -use crate::traversal::{AssignBSizes, AssignISizes, BubbleISizes}; -use crate::traversal::{PostorderFlowTraversal, PreorderFlowTraversal}; -use profile_traits::time::{self, profile, TimerMetadata}; +use block::BlockFlow; +use context::LayoutContext; +use flow::{Flow, GetBaseFlow}; +use flow_ref::FlowRef; +use profile_traits::time::{self, TimerMetadata, profile}; +use rayon; use servo_config::opts; use smallvec::SmallVec; use std::mem; use std::ptr; use std::sync::atomic::{AtomicIsize, Ordering}; +use traversal::{AssignBSizes, AssignISizes, BubbleISizes}; +use traversal::{PostorderFlowTraversal, PreorderFlowTraversal}; /// Traversal chunk size. const CHUNK_SIZE: usize = 16; @@ -28,7 +29,7 @@ pub type FlowList = SmallVec<[UnsafeFlow; CHUNK_SIZE]>; /// Vtable + pointer representation of a Flow trait object. #[derive(Clone, Copy, Eq, PartialEq)] -pub struct UnsafeFlow(*const dyn Flow); +pub struct UnsafeFlow(*const Flow); unsafe impl Sync for UnsafeFlow {} unsafe impl Send for UnsafeFlow {} @@ -72,7 +73,7 @@ impl FlowParallelInfo { fn bottom_up_flow(mut unsafe_flow: UnsafeFlow, assign_bsize_traversal: &AssignBSizes) { loop { // Get a real flow. - let flow: &mut dyn Flow = unsafe { mem::transmute(unsafe_flow) }; + let flow: &mut Flow = unsafe { mem::transmute(unsafe_flow) }; // Perform the appropriate traversal. if assign_bsize_traversal.should_process(flow) { @@ -96,7 +97,7 @@ fn bottom_up_flow(mut unsafe_flow: UnsafeFlow, assign_bsize_traversal: &AssignBS // No, we're not at the root yet. Then are we the last child // of our parent to finish processing? If so, we can continue // on with our parent; otherwise, we've gotta wait. - let parent: &mut dyn Flow = unsafe { &mut *(unsafe_parent.0 as *mut dyn Flow) }; + let parent: &mut Flow = unsafe { &mut *(unsafe_parent.0 as *mut Flow) }; let parent_base = parent.mut_base(); if parent_base .parallel @@ -126,7 +127,7 @@ fn top_down_flow<'scope>( let mut had_children = false; unsafe { // Get a real flow. - let flow: &mut dyn Flow = mem::transmute(*unsafe_flow); + let flow: &mut Flow = mem::transmute(*unsafe_flow); flow.mut_base().thread_id = pool.current_thread_index().unwrap() as u8; if assign_isize_traversal.should_process(flow) { @@ -190,7 +191,7 @@ fn top_down_flow<'scope>( /// Run the main layout passes in parallel. pub fn reflow( - root: &mut dyn Flow, + root: &mut Flow, profiler_metadata: Option, time_profiler_chan: time::ProfilerChan, context: &LayoutContext, diff --git a/components/layout/persistent_list.rs b/components/layout/persistent_list.rs index 735b2407ae51..0a8337bfaa7e 100644 --- a/components/layout/persistent_list.rs +++ b/components/layout/persistent_list.rs @@ -77,7 +77,7 @@ where pub struct PersistentListIterator<'a, T> where - T: Send + Sync, + T: 'a + Send + Sync, { entry: Option<&'a PersistentListEntry>, } diff --git a/components/layout/query.rs b/components/layout/query.rs index 1255e65bcbd9..f43ff0d61669 100644 --- a/components/layout/query.rs +++ b/components/layout/query.rs @@ -5,31 +5,28 @@ //! Utilities for querying the layout, as needed by the layout thread. use app_units::Au; -use crate::construct::ConstructionResult; -use crate::context::LayoutContext; -use crate::display_list::items::{DisplayList, OpaqueNode, ScrollOffsetMap}; -use crate::display_list::IndexableText; -use crate::flow::{Flow, GetBaseFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo}; -use crate::inline::InlineFragmentNodeFlags; -use crate::opaque_node::OpaqueNodeMethods; -use crate::sequential; -use crate::wrapper::LayoutNodeLayoutData; -use euclid::{Point2D, Rect, Size2D, Vector2D}; +use construct::ConstructionResult; +use context::LayoutContext; +use display_list::IndexableText; +use display_list::items::{DisplayList, OpaqueNode, ScrollOffsetMap}; +use euclid::{Point2D, Vector2D, Rect, Size2D}; +use flow::{Flow, GetBaseFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, SpecificFragmentInfo}; +use inline::InlineFragmentNodeFlags; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; -use script_layout_interface::rpc::TextIndexResponse; +use opaque_node::OpaqueNodeMethods; +use script_layout_interface::{LayoutElementType, LayoutNodeType}; +use script_layout_interface::StyleData; use script_layout_interface::rpc::{ContentBoxResponse, ContentBoxesResponse, LayoutRPC}; use script_layout_interface::rpc::{NodeGeometryResponse, NodeScrollIdResponse}; use script_layout_interface::rpc::{OffsetParentResponse, ResolvedStyleResponse, StyleResponse}; -use script_layout_interface::wrapper_traits::{ - LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode, -}; -use script_layout_interface::StyleData; -use script_layout_interface::{LayoutElementType, LayoutNodeType}; +use script_layout_interface::rpc::TextIndexResponse; +use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; use script_traits::LayoutMsg as ConstellationMsg; use script_traits::UntrustedNodeAddress; -use std::cmp::{max, min}; +use sequential; +use std::cmp::{min, max}; use std::ops::Deref; use std::sync::{Arc, Mutex}; use style::computed_values::display::T as Display; @@ -37,11 +34,12 @@ use style::computed_values::position::T as Position; use style::computed_values::visibility::T as Visibility; use style::context::{StyleContext, ThreadLocalStyleContext}; use style::dom::TElement; -use style::logical_geometry::{BlockFlowDirection, InlineBaseDirection, WritingMode}; -use style::properties::{style_structs, LonghandId, PropertyDeclarationId, PropertyId}; +use style::logical_geometry::{WritingMode, BlockFlowDirection, InlineBaseDirection}; +use style::properties::{style_structs, PropertyId, PropertyDeclarationId, LonghandId}; use style::selector_parser::PseudoElement; use style_traits::ToCss; use webrender_api::ExternalScrollId; +use wrapper::LayoutNodeLayoutData; /// Mutable data belonging to the LayoutThread. /// @@ -366,7 +364,7 @@ impl FragmentBorderBoxIterator for MarginRetrievingFragmentBorderBoxIterator { pub fn process_content_box_request( requested_node: N, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> Option> { // FIXME(pcwalton): This has not been updated to handle the stacking context relative // stuff. So the position is wrong in most cases. @@ -377,7 +375,7 @@ pub fn process_content_box_request( pub fn process_content_boxes_request( requested_node: N, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> Vec> { // FIXME(pcwalton): This has not been updated to handle the stacking context relative // stuff. So the position is wrong in most cases. @@ -605,7 +603,7 @@ impl FragmentBorderBoxIterator for ParentOffsetBorderBoxIterator { // cause this assertion to fail sometimes, so it's // commented out for now. /*assert!(node.flags.contains(FIRST_FRAGMENT_OF_ELEMENT), - "First fragment of inline node found wasn't its first fragment!");*/ + "First fragment of inline node found wasn't its first fragment!");*/ self.node_offset_box = Some(NodeOffsetBoxInfo { offset: border_box.origin, @@ -671,7 +669,7 @@ impl FragmentBorderBoxIterator for ParentOffsetBorderBoxIterator { pub fn process_node_geometry_request( requested_node: N, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> Rect { let mut iterator = FragmentLocatingFragmentIterator::new(requested_node.opaque()); sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator); @@ -689,7 +687,7 @@ pub fn process_node_scroll_id_request( /// https://drafts.csswg.org/cssom-view/#scrolling-area pub fn process_node_scroll_area_request( requested_node: N, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> Rect { let mut iterator = UnioningFragmentScrollAreaIterator::new(requested_node.opaque()); sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator); @@ -742,7 +740,7 @@ pub fn process_resolved_style_request<'a, N>( node: N, pseudo: &Option, property: &PropertyId, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> String where N: LayoutNode, @@ -791,7 +789,7 @@ fn process_resolved_style_request_internal<'a, N>( requested_node: N, pseudo: &Option, property: &PropertyId, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> String where N: LayoutNode, @@ -842,11 +840,12 @@ where let applies = true; fn used_value_for_position_property( - layout_el: ::ConcreteThreadSafeLayoutElement, - layout_root: &mut dyn Flow, - requested_node: N, - longhand_id: LonghandId, - ) -> String { + layout_el: ::ConcreteThreadSafeLayoutElement, + layout_root: &mut Flow, + requested_node: N, + longhand_id: LonghandId, + ) -> String + { let maybe_data = layout_el.borrow_layout_data(); let position = maybe_data.map_or(Point2D::zero(), |data| { match (*data).flow_construction_result { @@ -934,7 +933,7 @@ where pub fn process_offset_parent_query( requested_node: N, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, ) -> OffsetParentResponse { let mut iterator = ParentOffsetBorderBoxIterator::new(requested_node.opaque()); sequential::iterate_through_flow_tree_fragment_border_boxes(layout_root, &mut iterator); diff --git a/components/layout/sequential.rs b/components/layout/sequential.rs index 9ade33d97a7d..5da3f8426565 100644 --- a/components/layout/sequential.rs +++ b/components/layout/sequential.rs @@ -5,28 +5,28 @@ //! Implements sequential traversals over the DOM and flow trees. use app_units::Au; -use crate::context::LayoutContext; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; -use crate::floats::SpeculatedFloatPlacement; -use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; -use crate::fragment::{CoordinateSystem, FragmentBorderBoxIterator}; -use crate::generated_content::ResolveGeneratedContent; -use crate::incremental::RelayoutMode; -use crate::traversal::{AssignBSizes, AssignISizes, BubbleISizes, BuildDisplayList}; -use crate::traversal::{InorderFlowTraversal, PostorderFlowTraversal, PreorderFlowTraversal}; +use context::LayoutContext; +use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::{Point2D, Vector2D}; +use floats::SpeculatedFloatPlacement; +use flow::{Flow, ImmutableFlowUtils, FlowFlags, GetBaseFlow}; +use fragment::{FragmentBorderBoxIterator, CoordinateSystem}; +use generated_content::ResolveGeneratedContent; +use incremental::RelayoutMode; use servo_config::opts; use style::servo::restyle_damage::ServoRestyleDamage; +use traversal::{AssignBSizes, AssignISizes, BubbleISizes, BuildDisplayList}; +use traversal::{InorderFlowTraversal, PostorderFlowTraversal, PreorderFlowTraversal}; use webrender_api::LayoutPoint; -pub fn resolve_generated_content(root: &mut dyn Flow, layout_context: &LayoutContext) { +pub fn resolve_generated_content(root: &mut Flow, layout_context: &LayoutContext) { ResolveGeneratedContent::new(&layout_context).traverse(root, 0); } /// Run the main layout passes sequentially. -pub fn reflow(root: &mut dyn Flow, layout_context: &LayoutContext, relayout_mode: RelayoutMode) { +pub fn reflow(root: &mut Flow, layout_context: &LayoutContext, relayout_mode: RelayoutMode) { fn doit( - flow: &mut dyn Flow, + flow: &mut Flow, assign_inline_sizes: AssignISizes, assign_block_sizes: AssignBSizes, relayout_mode: RelayoutMode, @@ -70,7 +70,7 @@ pub fn reflow(root: &mut dyn Flow, layout_context: &LayoutContext, relayout_mode } pub fn build_display_list_for_subtree<'a>( - flow_root: &mut dyn Flow, + flow_root: &mut Flow, layout_context: &'a LayoutContext, ) -> DisplayListBuildState<'a> { let mut state = StackingContextCollectionState::new(layout_context.id); @@ -83,13 +83,13 @@ pub fn build_display_list_for_subtree<'a>( } pub fn iterate_through_flow_tree_fragment_border_boxes( - root: &mut dyn Flow, - iterator: &mut dyn FragmentBorderBoxIterator, + root: &mut Flow, + iterator: &mut FragmentBorderBoxIterator, ) { fn doit( - flow: &mut dyn Flow, + flow: &mut Flow, level: i32, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, stacking_context_position: &Point2D, ) { flow.iterate_through_fragment_border_boxes(iterator, level, stacking_context_position); @@ -119,7 +119,7 @@ pub fn iterate_through_flow_tree_fragment_border_boxes( doit(root, 0, iterator, &Point2D::zero()); } -pub fn store_overflow(layout_context: &LayoutContext, flow: &mut dyn Flow) { +pub fn store_overflow(layout_context: &LayoutContext, flow: &mut Flow) { if !flow .base() .restyle_damage @@ -142,7 +142,7 @@ pub fn store_overflow(layout_context: &LayoutContext, flow: &mut dyn Flow) { /// Guesses how much inline size will be taken up by floats on the left and right sides of the /// given flow. This is needed to speculatively calculate the inline sizes of block formatting /// contexts. The speculation typically succeeds, but if it doesn't we have to lay it out again. -pub fn guess_float_placement(flow: &mut dyn Flow) { +pub fn guess_float_placement(flow: &mut Flow) { if !flow .base() .restyle_damage diff --git a/components/layout/table.rs b/components/layout/table.rs index 10917628e753..cb80850e91e0 100644 --- a/components/layout/table.rs +++ b/components/layout/table.rs @@ -4,40 +4,37 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::{BlockFlow, CandidateBSizeIterator, ISizeAndMarginsComputer}; -use crate::block::{ISizeConstraintInput, ISizeConstraintSolution}; -use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; -use crate::display_list::{ - DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState, -}; -use crate::flow::{ - BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, - OpaqueFlow, -}; -use crate::flow_list::{FlowListIterator, MutFlowListIterator}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::model::{IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto}; -use crate::table_cell::TableCellFlow; -use crate::table_row::{self, CellIntrinsicInlineSize, CollapsedBorder, CollapsedBorderProvenance}; -use crate::table_row::{TableRowFlow, TableRowSizeData}; -use crate::table_wrapper::TableLayout; +use block::{BlockFlow, CandidateBSizeIterator, ISizeAndMarginsComputer}; +use block::{ISizeConstraintInput, ISizeConstraintSolution}; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, BorderPaintingMode}; +use display_list::{DisplayListBuildState, StackingContextCollectionFlags, StackingContextCollectionState}; use euclid::Point2D; +use flow::{BaseFlow, EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, GetBaseFlow, OpaqueFlow}; +use flow_list::{FlowListIterator, MutFlowListIterator}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; +use layout_debug; +use model::{IntrinsicISizes, IntrinsicISizesContribution, MaybeAuto}; use std::{cmp, fmt}; use style::computed_values::{border_collapse, border_spacing, table_layout}; use style::context::SharedStyleContext; use style::logical_geometry::LogicalSize; -use style::properties::style_structs::Background; use style::properties::ComputedValues; +use style::properties::style_structs::Background; use style::servo::restyle_damage::ServoRestyleDamage; -use style::values::computed::LengthOrPercentageOrAuto; use style::values::CSSFloat; +use style::values::computed::LengthOrPercentageOrAuto; +use table_cell::TableCellFlow; +use table_row::{self, CellIntrinsicInlineSize, CollapsedBorder, CollapsedBorderProvenance}; +use table_row::{TableRowFlow, TableRowSizeData}; +use table_wrapper::TableLayout; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableFlow {} +unsafe impl ::flow::HasBaseFlow for TableFlow {} /// A table flow corresponded to the table's internal table fragment under a table wrapper flow. /// The properties `position`, `float`, and `margin-*` are used on the table wrapper fragment, @@ -601,7 +598,7 @@ impl Flow for TableFlow { ); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -611,7 +608,7 @@ impl Flow for TableFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -622,7 +619,7 @@ impl Flow for TableFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } diff --git a/components/layout/table_caption.rs b/components/layout/table_caption.rs index 910ad7f8c5ba..51a6078ec319 100644 --- a/components/layout/table_caption.rs +++ b/components/layout/table_caption.rs @@ -4,21 +4,23 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::BlockFlow; -use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; -use crate::display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{Flow, FlowClass, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; +use block::BlockFlow; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; +use display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; use euclid::Point2D; +use flow::{Flow, FlowClass, OpaqueFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableCaptionFlow {} +unsafe impl ::flow::HasBaseFlow for TableCaptionFlow {} /// A table formatting context. #[repr(C)] @@ -93,7 +95,7 @@ impl Flow for TableCaptionFlow { .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -115,7 +117,7 @@ impl Flow for TableCaptionFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -126,7 +128,7 @@ impl Flow for TableCaptionFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } diff --git a/components/layout/table_cell.rs b/components/layout/table_cell.rs index 879ab9b82a18..1af32166a5f9 100644 --- a/components/layout/table_cell.rs +++ b/components/layout/table_cell.rs @@ -4,19 +4,19 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; -use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; -use crate::display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::model::MaybeAuto; -use crate::table::InternalTable; -use crate::table_row::{CollapsedBorder, CollapsedBorderProvenance}; +use block::{BlockFlow, ISizeAndMarginsComputer, MarginsMayCollapseFlag}; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; +use display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; use euclid::{Point2D, Rect, SideOffsets2D, Size2D}; +use flow::{Flow, FlowClass, FlowFlags, GetBaseFlow, OpaqueFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; +use layout_debug; +use model::MaybeAuto; use script_layout_interface::wrapper_traits::ThreadSafeLayoutNode; use std::fmt; use style::logical_geometry::{LogicalMargin, LogicalRect, LogicalSize, WritingMode}; @@ -24,9 +24,11 @@ use style::properties::ComputedValues; use style::values::computed::Color; use style::values::generics::box_::VerticalAlign; use style::values::specified::BorderStyle; +use table::InternalTable; +use table_row::{CollapsedBorder, CollapsedBorderProvenance}; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableCellFlow {} +unsafe impl ::flow::HasBaseFlow for TableCellFlow {} /// A table formatting context. #[derive(Serialize)] @@ -197,8 +199,7 @@ impl Flow for TableCellFlow { let specified_inline_size = MaybeAuto::from_style( self.block_flow.fragment.style().content_inline_size(), Au(0), - ) - .specified_or_zero(); + ).specified_or_zero(); if self .block_flow .base @@ -312,7 +313,7 @@ impl Flow for TableCellFlow { .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -334,7 +335,7 @@ impl Flow for TableCellFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -345,7 +346,7 @@ impl Flow for TableCellFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } diff --git a/components/layout/table_colgroup.rs b/components/layout/table_colgroup.rs index b2fd17d19786..7a3b54a2ed0c 100644 --- a/components/layout/table_colgroup.rs +++ b/components/layout/table_colgroup.rs @@ -4,20 +4,22 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::context::LayoutContext; -use crate::display_list::{DisplayListBuildState, StackingContextCollectionState}; -use crate::flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; +use context::LayoutContext; +use display_list::{DisplayListBuildState, StackingContextCollectionState}; use euclid::Point2D; +use flow::{BaseFlow, Flow, FlowClass, ForceNonfloatedFlag, OpaqueFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; +use layout_debug; use std::fmt; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; use style::values::computed::LengthOrPercentageOrAuto; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableColGroupFlow {} +unsafe impl ::flow::HasBaseFlow for TableColGroupFlow {} /// A table formatting context. #[repr(C)] @@ -100,7 +102,7 @@ impl Flow for TableColGroupFlow { self.base.clipping_and_scrolling = Some(state.current_clipping_and_scrolling); } - fn repair_style(&mut self, _: &crate::ServoArc) {} + fn repair_style(&mut self, _: &::ServoArc) {} fn compute_overflow(&self) -> Overflow { Overflow::new() @@ -112,13 +114,13 @@ impl Flow for TableColGroupFlow { fn iterate_through_fragment_border_boxes( &self, - _: &mut dyn FragmentBorderBoxIterator, + _: &mut FragmentBorderBoxIterator, _: i32, _: &Point2D, ) { } - fn mutate_fragments(&mut self, _: &mut dyn FnMut(&mut Fragment)) {} + fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {} } impl fmt::Debug for TableColGroupFlow { diff --git a/components/layout/table_row.rs b/components/layout/table_row.rs index ba327bd266ba..9d5c3a156181 100644 --- a/components/layout/table_row.rs +++ b/components/layout/table_row.rs @@ -4,22 +4,20 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::{BlockFlow, ISizeAndMarginsComputer}; -use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; -use crate::display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{ - EarlyAbsolutePositionInfo, Flow, FlowClass, GetBaseFlow, ImmutableFlowUtils, OpaqueFlow, -}; -use crate::flow_list::MutFlowListIterator; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::model::MaybeAuto; -use crate::table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable, VecExt}; -use crate::table_cell::{CollapsedBordersForCell, TableCellFlow}; +use block::{BlockFlow, ISizeAndMarginsComputer}; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; +use display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; use euclid::Point2D; +use flow::{EarlyAbsolutePositionInfo, Flow, FlowClass, ImmutableFlowUtils, GetBaseFlow, OpaqueFlow}; +use flow_list::MutFlowListIterator; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; +use layout_debug; +use model::MaybeAuto; use serde::{Serialize, Serializer}; use std::cmp::max; use std::fmt; @@ -30,9 +28,11 @@ use style::computed_values::border_top_style::T as BorderStyle; use style::logical_geometry::{LogicalSize, PhysicalSide, WritingMode}; use style::properties::ComputedValues; use style::values::computed::{Color, LengthOrPercentageOrAuto}; +use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize, InternalTable, VecExt}; +use table_cell::{CollapsedBordersForCell, TableCellFlow}; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableRowFlow {} +unsafe impl ::flow::HasBaseFlow for TableRowFlow {} /// A single row of a table. #[repr(C)] @@ -628,7 +628,7 @@ impl Flow for TableRowFlow { .collect_stacking_contexts_for_block(state, StackingContextCollectionFlags::empty()); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -650,7 +650,7 @@ impl Flow for TableRowFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -661,7 +661,7 @@ impl Flow for TableRowFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } @@ -907,7 +907,7 @@ impl CollapsedBorder { /// Pushes column inline size, incoming rowspan, and border collapse info down to a child. pub fn propagate_column_inline_sizes_to_child( - child_flow: &mut dyn Flow, + child_flow: &mut Flow, table_writing_mode: WritingMode, column_computed_inline_sizes: &[ColumnComputedInlineSize], border_spacing: &BorderSpacing, @@ -975,7 +975,7 @@ pub fn propagate_column_inline_sizes_to_child( /// Lay out table cells inline according to the computer column sizes. fn set_inline_position_of_child_flow( - child_flow: &mut dyn Flow, + child_flow: &mut Flow, child_index: usize, column_index: &mut usize, incoming_rowspan: &[u32], diff --git a/components/layout/table_rowgroup.rs b/components/layout/table_rowgroup.rs index 947bfde2d64d..3d77aca93823 100644 --- a/components/layout/table_rowgroup.rs +++ b/components/layout/table_rowgroup.rs @@ -4,26 +4,28 @@ //! CSS table formatting contexts. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::{BlockFlow, ISizeAndMarginsComputer}; -use crate::context::LayoutContext; -use crate::display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; -use crate::display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; -use crate::flow::{Flow, FlowClass, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::layout_debug; -use crate::table::{ColumnIntrinsicInlineSize, InternalTable, TableLikeFlow}; +use block::{BlockFlow, ISizeAndMarginsComputer}; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState}; +use display_list::{StackingContextCollectionFlags, StackingContextCollectionState}; use euclid::Point2D; +use flow::{Flow, FlowClass, OpaqueFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; +use layout_debug; use serde::{Serialize, Serializer}; use std::fmt; use std::iter::{IntoIterator, Iterator, Peekable}; use style::computed_values::{border_collapse, border_spacing}; use style::logical_geometry::LogicalSize; use style::properties::ComputedValues; +use table::{ColumnIntrinsicInlineSize, InternalTable, TableLikeFlow}; #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableRowGroupFlow {} +unsafe impl ::flow::HasBaseFlow for TableRowGroupFlow {} /// A table formatting context. #[repr(C)] @@ -224,7 +226,7 @@ impl Flow for TableRowGroupFlow { ); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -246,7 +248,7 @@ impl Flow for TableRowGroupFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -257,7 +259,7 @@ impl Flow for TableRowGroupFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } diff --git a/components/layout/table_wrapper.rs b/components/layout/table_wrapper.rs index 12683ee89462..65684f8e1651 100644 --- a/components/layout/table_wrapper.rs +++ b/components/layout/table_wrapper.rs @@ -11,23 +11,20 @@ //! //! Hereafter this document is referred to as INTRINSIC. +#![deny(unsafe_code)] + use app_units::Au; -use crate::block::{ - AbsoluteNonReplaced, BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput, -}; -use crate::block::{ISizeConstraintSolution, MarginsMayCollapseFlag}; -use crate::context::LayoutContext; -use crate::display_list::StackingContextCollectionState; -use crate::display_list::{ - BlockFlowDisplayListBuilding, DisplayListBuildState, StackingContextCollectionFlags, -}; -use crate::floats::FloatKind; -use crate::flow::{Flow, FlowClass, FlowFlags, ImmutableFlowUtils, OpaqueFlow}; -use crate::fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; -use crate::model::MaybeAuto; -use crate::table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize}; +use block::{AbsoluteNonReplaced, BlockFlow, FloatNonReplaced, ISizeAndMarginsComputer, ISizeConstraintInput}; +use block::{ISizeConstraintSolution, MarginsMayCollapseFlag}; +use context::LayoutContext; +use display_list::{BlockFlowDisplayListBuilding, DisplayListBuildState, StackingContextCollectionFlags}; +use display_list::StackingContextCollectionState; use euclid::Point2D; +use floats::FloatKind; +use flow::{Flow, FlowClass, ImmutableFlowUtils, FlowFlags, OpaqueFlow}; +use fragment::{Fragment, FragmentBorderBoxIterator, Overflow}; use gfx_traits::print_tree::PrintTree; +use model::MaybeAuto; use std::cmp::{max, min}; use std::fmt; use std::ops::Add; @@ -35,8 +32,9 @@ use style::computed_values::{position, table_layout}; use style::context::SharedStyleContext; use style::logical_geometry::{LogicalRect, LogicalSize}; use style::properties::ComputedValues; -use style::values::computed::LengthOrPercentageOrAuto; use style::values::CSSFloat; +use style::values::computed::LengthOrPercentageOrAuto; +use table::{ColumnComputedInlineSize, ColumnIntrinsicInlineSize}; #[derive(Clone, Copy, Debug, Serialize)] pub enum TableLayout { @@ -45,7 +43,7 @@ pub enum TableLayout { } #[allow(unsafe_code)] -unsafe impl crate::flow::HasBaseFlow for TableWrapperFlow {} +unsafe impl ::flow::HasBaseFlow for TableWrapperFlow {} /// A table wrapper flow based on a block formatting context. #[derive(Serialize)] @@ -147,8 +145,7 @@ impl TableWrapperFlow { ); total_guess = &total_guess + &guess; guess - }) - .collect(); + }).collect(); // Assign inline sizes. let selection = @@ -390,8 +387,7 @@ impl Flow for TableWrapperFlow { size: column_intrinsic_inline_size.minimum_length, percentage: column_intrinsic_inline_size.percentage, }, - ) - .collect::>(); + ).collect::>(); // Our inline-size was set to the inline-size of the containing block by the flow's parent. // Now compute the real value. @@ -521,7 +517,7 @@ impl Flow for TableWrapperFlow { ); } - fn repair_style(&mut self, new_style: &crate::ServoArc) { + fn repair_style(&mut self, new_style: &::ServoArc) { self.block_flow.repair_style(new_style) } @@ -531,7 +527,7 @@ impl Flow for TableWrapperFlow { fn iterate_through_fragment_border_boxes( &self, - iterator: &mut dyn FragmentBorderBoxIterator, + iterator: &mut FragmentBorderBoxIterator, level: i32, stacking_context_position: &Point2D, ) { @@ -542,7 +538,7 @@ impl Flow for TableWrapperFlow { ) } - fn mutate_fragments(&mut self, mutator: &mut dyn FnMut(&mut Fragment)) { + fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) { self.block_flow.mutate_fragments(mutator) } @@ -759,17 +755,17 @@ impl ExcessInlineSizeDistributionInfo { if !column_intrinsic_inline_size.constrained && column_intrinsic_inline_size.percentage == 0.0 { - self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage = self - .preferred_inline_size_of_nonconstrained_columns_with_no_percentage + - column_intrinsic_inline_size.preferred; + self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage = + self.preferred_inline_size_of_nonconstrained_columns_with_no_percentage + + column_intrinsic_inline_size.preferred; self.count_of_nonconstrained_columns_with_no_percentage += 1 } if column_intrinsic_inline_size.constrained && column_intrinsic_inline_size.percentage == 0.0 { - self.preferred_inline_size_of_constrained_columns_with_no_percentage = self - .preferred_inline_size_of_constrained_columns_with_no_percentage + - column_intrinsic_inline_size.preferred + self.preferred_inline_size_of_constrained_columns_with_no_percentage = + self.preferred_inline_size_of_constrained_columns_with_no_percentage + + column_intrinsic_inline_size.preferred } self.total_percentage += column_intrinsic_inline_size.percentage; self.column_count += 1 diff --git a/components/layout/tests/size_of.rs b/components/layout/tests/size_of.rs index 430053ca1605..7d8692713682 100644 --- a/components/layout/tests/size_of.rs +++ b/components/layout/tests/size_of.rs @@ -4,6 +4,7 @@ #![cfg(target_pointer_width = "64")] +extern crate layout; #[macro_use] extern crate size_of_test; diff --git a/components/layout/text.rs b/components/layout/text.rs index 6ba30eb2cc0d..c8321e9a03b9 100644 --- a/components/layout/text.rs +++ b/components/layout/text.rs @@ -4,16 +4,18 @@ //! Text layout. +#![deny(unsafe_code)] + use app_units::Au; -use crate::context::LayoutFontContext; -use crate::fragment::{Fragment, ScannedTextFlags}; -use crate::fragment::{ScannedTextFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; -use crate::inline::{InlineFragmentNodeFlags, InlineFragments}; -use crate::linked_list::split_off_head; -use gfx::font::{FontMetrics, FontRef, RunMetrics, ShapingFlags, ShapingOptions}; +use context::LayoutFontContext; +use fragment::{Fragment, ScannedTextFlags}; +use fragment::{ScannedTextFragmentInfo, SpecificFragmentInfo, UnscannedTextFragmentInfo}; +use gfx::font::{FontRef, FontMetrics, RunMetrics, ShapingFlags, ShapingOptions}; use gfx::text::glyph::ByteIndex; use gfx::text::text_run::TextRun; use gfx::text::util::{self, CompressionMode}; +use inline::{InlineFragmentNodeFlags, InlineFragments}; +use linked_list::split_off_head; use ordered_float::NotNan; use range::Range; use servo_atoms::Atom; @@ -26,11 +28,11 @@ use style::computed_values::text_transform::T as TextTransform; use style::computed_values::white_space::T as WhiteSpace; use style::computed_values::word_break::T as WordBreak; use style::logical_geometry::{LogicalSize, WritingMode}; -use style::properties::style_structs::Font as FontStyleStruct; use style::properties::ComputedValues; +use style::properties::style_structs::Font as FontStyleStruct; use style::values::generics::text::LineHeight; use unicode_bidi as bidi; -use unicode_script::{get_script, Script}; +use unicode_script::{Script, get_script}; use xi_unicode::LineBreakLeafIter; /// Returns the concatenated text of a list of unscanned text fragments. @@ -508,7 +510,7 @@ fn bounding_box_for_run_metrics( #[inline] pub fn font_metrics_for_style( mut font_context: &mut LayoutFontContext, - style: crate::ServoArc, + style: ::ServoArc, ) -> FontMetrics { let font_group = font_context.font_group(style); let font = font_group.borrow_mut().first(&mut font_context); diff --git a/components/layout/traversal.rs b/components/layout/traversal.rs index 6e2e739d8db1..e1db809bd8fd 100644 --- a/components/layout/traversal.rs +++ b/components/layout/traversal.rs @@ -4,12 +4,10 @@ //! Traversals over the DOM and flow trees, running the layout computations. -use crate::construct::FlowConstructor; -use crate::context::LayoutContext; -use crate::display_list::DisplayListBuildState; -use crate::flow::{Flow, FlowFlags, GetBaseFlow, ImmutableFlowUtils}; -use crate::wrapper::ThreadSafeLayoutNodeHelpers; -use crate::wrapper::{GetRawData, LayoutNodeLayoutData}; +use construct::FlowConstructor; +use context::LayoutContext; +use display_list::DisplayListBuildState; +use flow::{FlowFlags, Flow, GetBaseFlow, ImmutableFlowUtils}; use script_layout_interface::wrapper_traits::{LayoutNode, ThreadSafeLayoutNode}; use servo_config::opts; use style::context::{SharedStyleContext, StyleContext}; @@ -17,8 +15,10 @@ use style::data::ElementData; use style::dom::{NodeInfo, TElement, TNode}; use style::selector_parser::RestyleDamage; use style::servo::restyle_damage::ServoRestyleDamage; +use style::traversal::{DomTraversal, recalc_style_at}; use style::traversal::PerLevelTraversalData; -use style::traversal::{recalc_style_at, DomTraversal}; +use wrapper::{GetRawData, LayoutNodeLayoutData}; +use wrapper::ThreadSafeLayoutNodeHelpers; pub struct RecalcStyleAndConstructFlows<'a> { context: LayoutContext<'a>, @@ -90,23 +90,23 @@ where /// A top-down traversal. pub trait PreorderFlowTraversal { /// The operation to perform. Return true to continue or false to stop. - fn process(&self, flow: &mut dyn Flow); + fn process(&self, flow: &mut Flow); /// Returns true if this node should be processed and false if neither this node nor its /// descendants should be processed. - fn should_process_subtree(&self, _flow: &mut dyn Flow) -> bool { + fn should_process_subtree(&self, _flow: &mut Flow) -> bool { true } /// Returns true if this node must be processed in-order. If this returns false, /// we skip the operation for this node, but continue processing the descendants. /// This is called *after* parent nodes are visited. - fn should_process(&self, _flow: &mut dyn Flow) -> bool { + fn should_process(&self, _flow: &mut Flow) -> bool { true } /// Traverses the tree in preorder. - fn traverse(&self, flow: &mut dyn Flow) { + fn traverse(&self, flow: &mut Flow) { if !self.should_process_subtree(flow) { return; } @@ -124,7 +124,7 @@ pub trait PreorderFlowTraversal { /// their direct absolute descendants. /// /// Return true if the traversal is to continue or false to stop. - fn traverse_absolute_flows(&self, flow: &mut dyn Flow) { + fn traverse_absolute_flows(&self, flow: &mut Flow) { if self.should_process(flow) { self.process(flow); } @@ -137,17 +137,17 @@ pub trait PreorderFlowTraversal { /// A bottom-up traversal, with a optional in-order pass. pub trait PostorderFlowTraversal { /// The operation to perform. Return true to continue or false to stop. - fn process(&self, flow: &mut dyn Flow); + fn process(&self, flow: &mut Flow); /// Returns false if this node must be processed in-order. If this returns false, we skip the /// operation for this node, but continue processing the ancestors. This is called *after* /// child nodes are visited. - fn should_process(&self, _flow: &mut dyn Flow) -> bool { + fn should_process(&self, _flow: &mut Flow) -> bool { true } /// Traverses the tree in postorder. - fn traverse(&self, flow: &mut dyn Flow) { + fn traverse(&self, flow: &mut Flow) { for kid in flow.mut_base().child_iter_mut() { self.traverse(kid); } @@ -160,16 +160,16 @@ pub trait PostorderFlowTraversal { /// An in-order (sequential only) traversal. pub trait InorderFlowTraversal { /// The operation to perform. Returns the level of the tree we're at. - fn process(&mut self, flow: &mut dyn Flow, level: u32); + fn process(&mut self, flow: &mut Flow, level: u32); /// Returns true if this node should be processed and false if neither this node nor its /// descendants should be processed. - fn should_process_subtree(&mut self, _flow: &mut dyn Flow) -> bool { + fn should_process_subtree(&mut self, _flow: &mut Flow) -> bool { true } /// Traverses the tree in-order. - fn traverse(&mut self, flow: &mut dyn Flow, level: u32) { + fn traverse(&mut self, flow: &mut Flow, level: u32) { if !self.should_process_subtree(flow) { return; } @@ -220,7 +220,7 @@ where .mutate_layout_data() .unwrap() .flags - .insert(crate::data::LayoutDataFlags::HAS_BEEN_TRAVERSED); + .insert(::data::LayoutDataFlags::HAS_BEEN_TRAVERSED); } if let Some(el) = node.as_element() { @@ -238,7 +238,7 @@ pub struct BubbleISizes<'a> { impl<'a> PostorderFlowTraversal for BubbleISizes<'a> { #[inline] - fn process(&self, flow: &mut dyn Flow) { + fn process(&self, flow: &mut Flow) { flow.bubble_inline_sizes(); flow.mut_base() .restyle_damage @@ -246,7 +246,7 @@ impl<'a> PostorderFlowTraversal for BubbleISizes<'a> { } #[inline] - fn should_process(&self, flow: &mut dyn Flow) -> bool { + fn should_process(&self, flow: &mut Flow) -> bool { flow.base() .restyle_damage .contains(ServoRestyleDamage::BUBBLE_ISIZES) @@ -261,12 +261,12 @@ pub struct AssignISizes<'a> { impl<'a> PreorderFlowTraversal for AssignISizes<'a> { #[inline] - fn process(&self, flow: &mut dyn Flow) { + fn process(&self, flow: &mut Flow) { flow.assign_inline_sizes(self.layout_context); } #[inline] - fn should_process(&self, flow: &mut dyn Flow) -> bool { + fn should_process(&self, flow: &mut Flow) -> bool { flow.base() .restyle_damage .intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) @@ -283,7 +283,7 @@ pub struct AssignBSizes<'a> { impl<'a> PostorderFlowTraversal for AssignBSizes<'a> { #[inline] - fn process(&self, flow: &mut dyn Flow) { + fn process(&self, flow: &mut Flow) { // Can't do anything with anything that floats might flow through until we reach their // inorder parent. // @@ -297,7 +297,7 @@ impl<'a> PostorderFlowTraversal for AssignBSizes<'a> { } #[inline] - fn should_process(&self, flow: &mut dyn Flow) -> bool { + fn should_process(&self, flow: &mut Flow) -> bool { let base = flow.base(); base.restyle_damage.intersects(ServoRestyleDamage::REFLOW_OUT_OF_FLOW | ServoRestyleDamage::REFLOW) && // The fragmentation countainer is responsible for calling @@ -312,14 +312,14 @@ pub struct ComputeStackingRelativePositions<'a> { impl<'a> PreorderFlowTraversal for ComputeStackingRelativePositions<'a> { #[inline] - fn should_process_subtree(&self, flow: &mut dyn Flow) -> bool { + fn should_process_subtree(&self, flow: &mut Flow) -> bool { flow.base() .restyle_damage .contains(ServoRestyleDamage::REPOSITION) } #[inline] - fn process(&self, flow: &mut dyn Flow) { + fn process(&self, flow: &mut Flow) { flow.compute_stacking_relative_position(self.layout_context); flow.mut_base() .restyle_damage @@ -333,7 +333,7 @@ pub struct BuildDisplayList<'a> { impl<'a> BuildDisplayList<'a> { #[inline] - pub fn traverse(&mut self, flow: &mut dyn Flow) { + pub fn traverse(&mut self, flow: &mut Flow) { let parent_stacking_context_id = self.state.current_stacking_context_id; self.state.current_stacking_context_id = flow.base().stacking_context_id; diff --git a/components/layout/wrapper.rs b/components/layout/wrapper.rs index 82ffd6be718f..1e3f30f3f7cb 100644 --- a/components/layout/wrapper.rs +++ b/components/layout/wrapper.rs @@ -31,9 +31,9 @@ #![allow(unsafe_code)] use atomic_refcell::{AtomicRef, AtomicRefMut}; -use crate::data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; -use script_layout_interface::wrapper_traits::GetLayoutData; +use data::{LayoutData, LayoutDataFlags, StyleAndLayoutData}; use script_layout_interface::wrapper_traits::{ThreadSafeLayoutElement, ThreadSafeLayoutNode}; +use script_layout_interface::wrapper_traits::GetLayoutData; use style::dom::{NodeInfo, TNode}; use style::selector_parser::RestyleDamage; use style::values::computed::counters::ContentItem; @@ -144,7 +144,7 @@ impl ThreadSafeLayoutNodeHelpers for T { .layout_data .borrow() .flags - .contains(crate::data::LayoutDataFlags::HAS_BEEN_TRAVERSED) + .contains(::data::LayoutDataFlags::HAS_BEEN_TRAVERSED) { // We're reflowing a node that was styled for the first time and // has never been visited by layout. Return rebuild_and_reflow, diff --git a/components/layout_thread/Cargo.toml b/components/layout_thread/Cargo.toml index 30369ad27801..2c76600dbfb9 100644 --- a/components/layout_thread/Cargo.toml +++ b/components/layout_thread/Cargo.toml @@ -3,7 +3,6 @@ name = "layout_thread" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -54,3 +53,6 @@ servo_url = {path = "../url"} style = {path = "../style"} style_traits = {path = "../style_traits"} webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} + +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"] } diff --git a/components/layout_thread/dom_wrapper.rs b/components/layout_thread/dom_wrapper.rs index 21e61d96fff0..5900b912e736 100644 --- a/components/layout_thread/dom_wrapper.rs +++ b/components/layout_thread/dom_wrapper.rs @@ -30,35 +30,26 @@ #![allow(unsafe_code)] -use atomic_refcell::{AtomicRef, AtomicRefCell, AtomicRefMut}; +use atomic_refcell::{AtomicRef, AtomicRefMut, AtomicRefCell}; use gfx_traits::ByteIndex; use html5ever::{LocalName, Namespace}; use layout::data::StyleAndLayoutData; use layout::wrapper::GetRawData; use msg::constellation_msg::{BrowsingContextId, PipelineId}; -use net_traits::image::base::{Image, ImageMetadata}; use range::Range; -use script::layout_exports::NodeFlags; -use script::layout_exports::PendingRestyle; use script::layout_exports::{CharacterDataTypeId, ElementTypeId, HTMLElementTypeId, NodeTypeId}; use script::layout_exports::{Document, Element, Node, Text}; use script::layout_exports::{LayoutCharacterDataHelpers, LayoutDocumentHelpers}; -use script::layout_exports::{ - LayoutDom, LayoutElementHelpers, LayoutNodeHelpers, RawLayoutElementHelpers, -}; -use script_layout_interface::wrapper_traits::{ - DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode, -}; -use script_layout_interface::wrapper_traits::{ - PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode, -}; -use script_layout_interface::{ - HTMLCanvasData, HTMLMediaData, LayoutNodeType, OpaqueStyleAndLayoutData, -}; -use script_layout_interface::{SVGSVGData, StyleData, TrustedNodeAddress}; -use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint}; -use selectors::matching::VisitedHandlingMode; +use script::layout_exports::{LayoutElementHelpers, LayoutNodeHelpers, LayoutDom, RawLayoutElementHelpers}; +use script::layout_exports::NodeFlags; +use script::layout_exports::PendingRestyle; +use script_layout_interface::{HTMLCanvasData, LayoutNodeType, SVGSVGData, TrustedNodeAddress}; +use script_layout_interface::{OpaqueStyleAndLayoutData, StyleData}; +use script_layout_interface::wrapper_traits::{DangerousThreadSafeLayoutNode, GetLayoutData, LayoutNode}; +use script_layout_interface::wrapper_traits::{PseudoElementType, ThreadSafeLayoutElement, ThreadSafeLayoutNode}; +use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; use selectors::matching::{ElementSelectorFlags, MatchingContext, QuirksMode}; +use selectors::matching::VisitedHandlingMode; use selectors::sink::Push; use servo_arc::{Arc, ArcBorrow}; use servo_atoms::Atom; @@ -69,7 +60,7 @@ use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::ptr::NonNull; use std::sync::atomic::Ordering; -use std::sync::Arc as StdArc; +use style::CaseSensitivityExt; use style::applicable_declarations::ApplicableDeclarationBlock; use style::attr::AttrValue; use style::context::SharedStyleContext; @@ -79,12 +70,11 @@ use style::dom::{TDocument, TElement, TNode, TShadowRoot}; use style::element_state::*; use style::font_metrics::ServoMetricsProvider; use style::properties::{ComputedValues, PropertyDeclarationBlock}; -use style::selector_parser::{extended_filtering, PseudoElement, SelectorImpl}; -use style::selector_parser::{AttrValue as SelectorAttrValue, Lang, NonTSPseudoClass}; -use style::shared_lock::{Locked as StyleLocked, SharedRwLock as StyleSharedRwLock}; +use style::selector_parser::{AttrValue as SelectorAttrValue, NonTSPseudoClass, Lang}; +use style::selector_parser::{PseudoElement, SelectorImpl, extended_filtering}; +use style::shared_lock::{SharedRwLock as StyleSharedRwLock, Locked as StyleLocked}; use style::str::is_whitespace; use style::stylist::CascadeData; -use style::CaseSensitivityExt; pub unsafe fn drop_style_and_layout_data(data: OpaqueStyleAndLayoutData) { let ptr = data.ptr.as_ptr() as *mut StyleData; @@ -672,7 +662,7 @@ impl<'le> ServoLayoutElement<'le> { } pub unsafe fn note_dirty_descendant(&self) { - use selectors::Element; + use ::selectors::Element; let mut current = Some(*self); while let Some(el) = current { @@ -695,7 +685,9 @@ impl<'le> ::selectors::Element for ServoLayoutElement<'le> { type Impl = SelectorImpl; fn opaque(&self) -> ::selectors::OpaqueElement { - ::selectors::OpaqueElement::new(unsafe { &*(self.as_node().opaque().0 as *const ()) }) + ::selectors::OpaqueElement::new(unsafe { + &*(self.as_node().opaque().0 as *const ()) + }) } fn parent_element(&self) -> Option> { @@ -1056,21 +1048,11 @@ impl<'ln> ThreadSafeLayoutNode for ServoThreadSafeLayoutNode<'ln> { this.image_density() } - fn image_data(&self) -> Option<(Option>, Option)> { - let this = unsafe { self.get_jsmanaged() }; - this.image_data() - } - fn canvas_data(&self) -> Option { let this = unsafe { self.get_jsmanaged() }; this.canvas_data() } - fn media_data(&self) -> Option { - let this = unsafe { self.get_jsmanaged() }; - this.media_data() - } - fn svg_data(&self) -> Option { let this = unsafe { self.get_jsmanaged() }; this.svg_data() @@ -1140,7 +1122,7 @@ where { type Item = ConcreteNode; fn next(&mut self) -> Option { - use selectors::Element; + use ::selectors::Element; match self.parent_node.get_pseudo_element_type() { PseudoElementType::Before | PseudoElementType::After => None, @@ -1278,7 +1260,9 @@ impl<'le> ::selectors::Element for ServoThreadSafeLayoutElement<'le> { type Impl = SelectorImpl; fn opaque(&self) -> ::selectors::OpaqueElement { - ::selectors::OpaqueElement::new(unsafe { &*(self.as_node().opaque().0 as *const ()) }) + ::selectors::OpaqueElement::new(unsafe { + &*(self.as_node().opaque().0 as *const ()) + }) } fn parent_element(&self) -> Option { diff --git a/components/layout_thread/lib.rs b/components/layout_thread/lib.rs index 91b801464fe9..3057701f360c 100644 --- a/components/layout_thread/lib.rs +++ b/components/layout_thread/lib.rs @@ -5,24 +5,58 @@ //! The layout thread. Performs layout on the DOM, builds display lists and sends them to be //! painted. +extern crate app_units; +extern crate atomic_refcell; +extern crate embedder_traits; +extern crate euclid; +extern crate fnv; +extern crate fxhash; +extern crate gfx; +extern crate gfx_traits; +extern crate histogram; #[macro_use] extern crate html5ever; +extern crate ipc_channel; #[macro_use] extern crate layout; +extern crate layout_traits; #[macro_use] extern crate lazy_static; +extern crate libc; #[macro_use] extern crate log; +extern crate malloc_size_of; +extern crate metrics; +extern crate msg; +extern crate net_traits; +extern crate parking_lot; #[macro_use] extern crate profile_traits; +extern crate range; +extern crate rayon; +extern crate script; +extern crate script_layout_interface; +extern crate script_traits; +extern crate selectors; +extern crate serde_json; +extern crate servo_allocator; +extern crate servo_arc; +extern crate servo_atoms; #[macro_use] extern crate servo_channel; +extern crate servo_config; +extern crate servo_geometry; +extern crate servo_url; +extern crate style; +extern crate style_traits; +extern crate time as std_time; +extern crate webrender_api; mod dom_wrapper; use app_units::Au; -use crate::dom_wrapper::drop_style_and_layout_data; -use crate::dom_wrapper::{ServoLayoutDocument, ServoLayoutElement, ServoLayoutNode}; +use dom_wrapper::{ServoLayoutElement, ServoLayoutDocument, ServoLayoutNode}; +use dom_wrapper::drop_style_and_layout_data; use embedder_traits::resources::{self, Resource}; use euclid::{Point2D, Rect, Size2D, TypedScale, TypedSize2D}; use fnv::FnvHashMap; @@ -30,34 +64,28 @@ use fxhash::FxHashMap; use gfx::font; use gfx::font_cache_thread::FontCacheThread; use gfx::font_context; -use gfx_traits::{node_id_from_scroll_id, Epoch}; +use gfx_traits::{Epoch, node_id_from_scroll_id}; use histogram::Histogram; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use layout::animation; use layout::construct::ConstructionResult; -use layout::context::malloc_size_of_persistent_local_context; use layout::context::LayoutContext; use layout::context::RegisteredPainter; use layout::context::RegisteredPainters; -use layout::display_list::items::{OpaqueNode, WebRenderImageInfo}; +use layout::context::malloc_size_of_persistent_local_context; use layout::display_list::{IndexableText, ToLayout, WebRenderDisplayListConverter}; +use layout::display_list::items::{OpaqueNode, WebRenderImageInfo}; use layout::flow::{Flow, GetBaseFlow, ImmutableFlowUtils, MutableOwnedFlowUtils}; use layout::flow_ref::FlowRef; use layout::incremental::{LayoutDamageComputation, RelayoutMode, SpecialRestyleDamage}; use layout::layout_debug; use layout::parallel; -use layout::query::{ - process_content_box_request, process_content_boxes_request, LayoutRPCImpl, LayoutThreadData, -}; +use layout::query::{LayoutRPCImpl, LayoutThreadData, process_content_box_request, process_content_boxes_request}; use layout::query::{process_element_inner_text_query, process_node_geometry_request}; use layout::query::{process_node_scroll_area_request, process_node_scroll_id_request}; -use layout::query::{ - process_offset_parent_query, process_resolved_style_request, process_style_query, -}; +use layout::query::{process_offset_parent_query, process_resolved_style_request, process_style_query}; use layout::sequential; -use layout::traversal::{ - ComputeStackingRelativePositions, PreorderFlowTraversal, RecalcStyleAndConstructFlows, -}; +use layout::traversal::{ComputeStackingRelativePositions, PreorderFlowTraversal, RecalcStyleAndConstructFlows}; use layout::wrapper::LayoutNodeLayoutData; use layout_traits::LayoutThreadFactory; use libc::c_void; @@ -67,22 +95,22 @@ use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; use net_traits::image_cache::{ImageCache, UsePlaceholder}; use parking_lot::RwLock; -use profile_traits::mem::{self as profile_mem, Report, ReportKind, ReportsChan}; -use profile_traits::time::{self as profile_time, profile, TimerMetadata}; +use profile_traits::mem::{self, Report, ReportKind, ReportsChan}; +use profile_traits::time::{self, TimerMetadata, profile}; use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType}; use script_layout_interface::message::{Msg, NewLayoutThreadInfo, NodesFromPointQueryType, Reflow}; -use script_layout_interface::message::{QueryMsg, ReflowComplete, ReflowGoal, ScriptReflow}; +use script_layout_interface::message::{ReflowComplete, QueryMsg, ReflowGoal, ScriptReflow}; +use script_layout_interface::rpc::{LayoutRPC, StyleResponse, OffsetParentResponse}; use script_layout_interface::rpc::TextIndexResponse; -use script_layout_interface::rpc::{LayoutRPC, OffsetParentResponse, StyleResponse}; use script_layout_interface::wrapper_traits::LayoutNode; -use script_traits::Painter; use script_traits::{ConstellationControlMsg, LayoutControlMsg, LayoutMsg as ConstellationMsg}; use script_traits::{DrawAPaintImageResult, PaintWorkletError}; use script_traits::{ScrollState, UntrustedNodeAddress}; +use script_traits::Painter; use selectors::Element; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; -use servo_channel::{channel, route_ipc_receiver_to_new_servo_receiver, Receiver, Sender}; +use servo_channel::{Receiver, Sender, channel, route_ipc_receiver_to_new_servo_receiver}; use servo_config::opts; use servo_config::prefs::PREFS; use servo_geometry::MaxRect; @@ -90,10 +118,11 @@ use servo_url::ServoUrl; use std::borrow::ToOwned; use std::cell::{Cell, RefCell}; use std::collections::HashMap; +use std::mem as std_mem; use std::ops::{Deref, DerefMut}; use std::process; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::thread; use style::animation::Animation; use style::context::{QuirksMode, RegisteredSpeculativePainter, RegisteredSpeculativePainters}; @@ -108,9 +137,7 @@ use style::properties::PropertyId; use style::selector_parser::SnapshotMap; use style::servo::restyle_damage::ServoRestyleDamage; use style::shared_lock::{SharedRwLock, SharedRwLockReadGuard, StylesheetGuards}; -use style::stylesheets::{ - DocumentStyleSheet, Origin, Stylesheet, StylesheetInDocument, UserAgentStylesheets, -}; +use style::stylesheets::{Origin, Stylesheet, DocumentStyleSheet, StylesheetInDocument, UserAgentStylesheets}; use style::stylist::Stylist; use style::thread_state::{self, ThreadState}; use style::timer::Timer; @@ -156,13 +183,13 @@ pub struct LayoutThread { script_chan: IpcSender, /// The channel on which messages can be sent to the time profiler. - time_profiler_chan: profile_time::ProfilerChan, + time_profiler_chan: time::ProfilerChan, /// The channel on which messages can be sent to the memory profiler. - mem_profiler_chan: profile_mem::ProfilerChan, + mem_profiler_chan: mem::ProfilerChan, /// Reference to the script thread image cache. - image_cache: Arc, + image_cache: Arc, /// Public interface to the font cache thread. font_cache_thread: FontCacheThread, @@ -254,10 +281,10 @@ impl LayoutThreadFactory for LayoutThread { pipeline_port: IpcReceiver, constellation_chan: IpcSender, script_chan: IpcSender, - image_cache: Arc, + image_cache: Arc, font_cache_thread: FontCacheThread, - time_profiler_chan: profile_time::ProfilerChan, - mem_profiler_chan: profile_mem::ProfilerChan, + time_profiler_chan: time::ProfilerChan, + mem_profiler_chan: mem::ProfilerChan, content_process_shutdown_chan: Option>, webrender_api_sender: webrender_api::RenderApiSender, webrender_document: webrender_api::DocumentId, @@ -307,8 +334,7 @@ impl LayoutThreadFactory for LayoutThread { if let Some(content_process_shutdown_chan) = content_process_shutdown_chan { let _ = content_process_shutdown_chan.send(()); } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } } @@ -445,10 +471,10 @@ impl LayoutThread { pipeline_port: IpcReceiver, constellation_chan: IpcSender, script_chan: IpcSender, - image_cache: Arc, + image_cache: Arc, font_cache_thread: FontCacheThread, - time_profiler_chan: profile_time::ProfilerChan, - mem_profiler_chan: profile_mem::ProfilerChan, + time_profiler_chan: time::ProfilerChan, + mem_profiler_chan: mem::ProfilerChan, webrender_api_sender: webrender_api::RenderApiSender, webrender_document: webrender_api::DocumentId, layout_threads: usize, @@ -481,7 +507,8 @@ impl LayoutThread { // Ask the router to proxy IPC messages from the font cache thread to the layout thread. let (ipc_font_cache_sender, ipc_font_cache_receiver) = ipc::channel().unwrap(); - let font_cache_receiver = route_ipc_receiver_to_new_servo_receiver(ipc_font_cache_receiver); + let font_cache_receiver = + route_ipc_receiver_to_new_servo_receiver(ipc_font_cache_receiver); LayoutThread { id: id, @@ -681,13 +708,13 @@ impl LayoutThread { Msg::SetQuirksMode(mode) => self.handle_set_quirks_mode(mode), Msg::GetRPC(response_chan) => { response_chan - .send(Box::new(LayoutRPCImpl(self.rw_data.clone())) as Box) + .send(Box::new(LayoutRPCImpl(self.rw_data.clone())) as Box) .unwrap(); }, Msg::Reflow(data) => { let mut data = ScriptReflowResult::new(data); profile( - profile_time::ProfilerCategory::LayoutPerform, + time::ProfilerCategory::LayoutPerform, self.profiler_metadata(), self.time_profiler_chan.clone(), || self.handle_reflow(&mut data, possibly_locked_rw_data), @@ -742,8 +769,7 @@ impl LayoutThread { .filter_map(|name| { let id = PropertyId::parse_enabled_for_all_content(&*name).ok()?; Some((name.clone(), id)) - }) - .filter(|&(_, ref id)| !id.is_shorthand()) + }).filter(|&(_, ref id)| !id.is_shorthand()) .collect(); let registered_painter = RegisteredPainterImpl { name: name.clone(), @@ -777,7 +803,7 @@ impl LayoutThread { let mut reports = vec![]; // Servo uses vanilla jemalloc, which doesn't have a // malloc_enclosing_size_of function. - let mut ops = MallocSizeOfOps::new(servo_allocator::usable_size, None, None); + let mut ops = MallocSizeOfOps::new(::servo_allocator::usable_size, None, None); // FIXME(njn): Just measuring the display tree for now. let rw_data = possibly_locked_rw_data.lock(); @@ -928,7 +954,7 @@ impl LayoutThread { /// This corresponds to `Reflow()` in Gecko and `layout()` in WebKit/Blink and should be /// benchmarked against those two. It is marked `#[inline(never)]` to aid profiling. #[inline(never)] - fn solve_constraints(layout_root: &mut dyn Flow, layout_context: &LayoutContext) { + fn solve_constraints(layout_root: &mut Flow, layout_context: &LayoutContext) { let _scope = layout_debug_scope!("solve_constraints"); sequential::reflow(layout_root, layout_context, RelayoutMode::Incremental); } @@ -940,9 +966,9 @@ impl LayoutThread { #[inline(never)] fn solve_constraints_parallel( traversal: &rayon::ThreadPool, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, profiler_metadata: Option, - time_profiler_chan: profile_time::ProfilerChan, + time_profiler_chan: time::ProfilerChan, layout_context: &LayoutContext, ) { let _scope = layout_debug_scope!("solve_constraints_parallel"); @@ -965,14 +991,14 @@ impl LayoutThread { data: &Reflow, reflow_goal: &ReflowGoal, document: Option<&ServoLayoutDocument>, - layout_root: &mut dyn Flow, + layout_root: &mut Flow, layout_context: &mut LayoutContext, rw_data: &mut LayoutThreadData, ) { let writing_mode = layout_root.base().writing_mode; let (metadata, sender) = (self.profiler_metadata(), self.time_profiler_chan.clone()); profile( - profile_time::ProfilerCategory::LayoutDispListBuild, + time::ProfilerCategory::LayoutDispListBuild, metadata.clone(), sender.clone(), || { @@ -1114,7 +1140,7 @@ impl LayoutThread { let mut rw_data = possibly_locked_rw_data.lock(); // Record the time that layout query has been waited. - let now = time::precise_time_ns(); + let now = std_time::precise_time_ns(); if let ReflowGoal::LayoutQuery(_, timestamp) = data.reflow_goal { self.layout_query_waiting_time .increment(now - timestamp) @@ -1223,8 +1249,7 @@ impl LayoutThread { .send(ConstellationMsg::ViewportConstrained( self.id, constraints.clone(), - )) - .unwrap(); + )).unwrap(); } if had_used_viewport_units { if let Some(mut data) = element.mutate_data() { @@ -1331,7 +1356,7 @@ impl LayoutThread { if token.should_traverse() { // Recalculate CSS styles and rebuild flows and fragments. profile( - profile_time::ProfilerCategory::LayoutStyleRecalc, + time::ProfilerCategory::LayoutStyleRecalc, self.profiler_metadata(), self.time_profiler_chan.clone(), || { @@ -1346,8 +1371,8 @@ impl LayoutThread { // TODO(pcwalton): Measure energy usage of text shaping, perhaps? let text_shaping_time = (font::get_and_reset_text_shaping_performance_counter() as u64) / (self.layout_threads as u64); - profile_time::send_profile_data( - profile_time::ProfilerCategory::LayoutTextShaping, + time::send_profile_data( + time::ProfilerCategory::LayoutTextShaping, self.profiler_metadata(), &self.time_profiler_chan, 0, @@ -1412,13 +1437,13 @@ impl LayoutThread { reflow_result: &mut ReflowComplete, ) { let pending_images = match context.pending_images { - Some(ref pending) => std::mem::replace(&mut *pending.lock().unwrap(), vec![]), + Some(ref pending) => std_mem::replace(&mut *pending.lock().unwrap(), vec![]), None => vec![], }; reflow_result.pending_images = pending_images; let newly_transitioning_nodes = match context.newly_transitioning_nodes { - Some(ref nodes) => std::mem::replace(&mut *nodes.lock().unwrap(), vec![]), + Some(ref nodes) => std_mem::replace(&mut *nodes.lock().unwrap(), vec![]), None => vec![], }; reflow_result.newly_transitioning_nodes = newly_transitioning_nodes; @@ -1573,7 +1598,7 @@ impl LayoutThread { // Perform an abbreviated style recalc that operates without access to the DOM. let animations = self.running_animations.read(); profile( - profile_time::ProfilerCategory::LayoutStyleRecalc, + time::ProfilerCategory::LayoutStyleRecalc, self.profiler_metadata(), self.time_profiler_chan.clone(), || { @@ -1628,7 +1653,7 @@ impl LayoutThread { } profile( - profile_time::ProfilerCategory::LayoutRestyleDamagePropagation, + time::ProfilerCategory::LayoutRestyleDamagePropagation, self.profiler_metadata(), self.time_profiler_chan.clone(), || { @@ -1650,7 +1675,7 @@ impl LayoutThread { // Resolve generated content. profile( - profile_time::ProfilerCategory::LayoutGeneratedContent, + time::ProfilerCategory::LayoutGeneratedContent, self.profiler_metadata(), self.time_profiler_chan.clone(), || sequential::resolve_generated_content(FlowRef::deref_mut(root_flow), &context), @@ -1658,7 +1683,7 @@ impl LayoutThread { // Guess float placement. profile( - profile_time::ProfilerCategory::LayoutFloatPlacementSpeculation, + time::ProfilerCategory::LayoutFloatPlacementSpeculation, self.profiler_metadata(), self.time_profiler_chan.clone(), || sequential::guess_float_placement(FlowRef::deref_mut(root_flow)), @@ -1672,7 +1697,7 @@ impl LayoutThread { .intersects(ServoRestyleDamage::REFLOW | ServoRestyleDamage::REFLOW_OUT_OF_FLOW) { profile( - profile_time::ProfilerCategory::LayoutMain, + time::ProfilerCategory::LayoutMain, self.profiler_metadata(), self.time_profiler_chan.clone(), || { @@ -1698,11 +1723,11 @@ impl LayoutThread { } profile( - profile_time::ProfilerCategory::LayoutStoreOverflow, + time::ProfilerCategory::LayoutStoreOverflow, self.profiler_metadata(), self.time_profiler_chan.clone(), || { - sequential::store_overflow(context, FlowRef::deref_mut(root_flow) as &mut dyn Flow); + sequential::store_overflow(context, FlowRef::deref_mut(root_flow) as &mut Flow); }, ); @@ -1746,7 +1771,7 @@ impl LayoutThread { self.generation.set(self.generation.get() + 1); } - fn reflow_all_nodes(flow: &mut dyn Flow) { + fn reflow_all_nodes(flow: &mut Flow) { debug!("reflowing all nodes!"); flow.mut_base().restyle_damage.insert( ServoRestyleDamage::REPAINT | @@ -1793,7 +1818,7 @@ impl ProfilerMetadataFactory for LayoutThread { // clearing the frame buffer to white. This ensures that setting a background // color on an iframe element, while the iframe content itself has a default // transparent background color is handled correctly. -fn get_root_flow_background_color(flow: &mut dyn Flow) -> webrender_api::ColorF { +fn get_root_flow_background_color(flow: &mut Flow) -> webrender_api::ColorF { let transparent = webrender_api::ColorF { r: 0.0, g: 0.0, @@ -1913,7 +1938,7 @@ lazy_static! { } struct RegisteredPainterImpl { - painter: Box, + painter: Box, name: Atom, // FIXME: Should be a PrecomputedHashMap. properties: FxHashMap, @@ -1957,17 +1982,17 @@ impl RegisteredPainter for RegisteredPainterImpl {} struct RegisteredPaintersImpl(FnvHashMap); impl RegisteredSpeculativePainters for RegisteredPaintersImpl { - fn get(&self, name: &Atom) -> Option<&dyn RegisteredSpeculativePainter> { + fn get(&self, name: &Atom) -> Option<&RegisteredSpeculativePainter> { self.0 .get(&name) - .map(|painter| painter as &dyn RegisteredSpeculativePainter) + .map(|painter| painter as &RegisteredSpeculativePainter) } } impl RegisteredPainters for RegisteredPaintersImpl { - fn get(&self, name: &Atom) -> Option<&dyn RegisteredPainter> { + fn get(&self, name: &Atom) -> Option<&RegisteredPainter> { self.0 .get(&name) - .map(|painter| painter as &dyn RegisteredPainter) + .map(|painter| painter as &RegisteredPainter) } } diff --git a/components/layout_traits/Cargo.toml b/components/layout_traits/Cargo.toml index 881e67315e84..162c7add7b43 100644 --- a/components/layout_traits/Cargo.toml +++ b/components/layout_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "layout_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/layout_traits/lib.rs b/components/layout_traits/lib.rs index 8ecf214fbb0a..646706e77179 100644 --- a/components/layout_traits/lib.rs +++ b/components/layout_traits/lib.rs @@ -4,6 +4,17 @@ #![deny(unsafe_code)] +extern crate gfx; +extern crate ipc_channel; +extern crate metrics; +extern crate msg; +extern crate net_traits; +extern crate profile_traits; +extern crate script_traits; +extern crate servo_channel; +extern crate servo_url; +extern crate webrender_api; + // This module contains traits in layout used generically // in the rest of Servo. // The traits are here instead of in layout so @@ -16,8 +27,8 @@ use msg::constellation_msg::PipelineId; use msg::constellation_msg::TopLevelBrowsingContextId; use net_traits::image_cache::ImageCache; use profile_traits::{mem, time}; -use script_traits::LayoutMsg as ConstellationMsg; use script_traits::{ConstellationControlMsg, LayoutControlMsg}; +use script_traits::LayoutMsg as ConstellationMsg; use servo_channel::{Receiver, Sender}; use servo_url::ServoUrl; use std::sync::Arc; @@ -35,7 +46,7 @@ pub trait LayoutThreadFactory { pipeline_port: IpcReceiver, constellation_chan: IpcSender, script_chan: IpcSender, - image_cache: Arc, + image_cache: Arc, font_cache_thread: FontCacheThread, time_profiler_chan: time::ProfilerChan, mem_profiler_chan: mem::ProfilerChan, diff --git a/components/malloc_size_of/Cargo.toml b/components/malloc_size_of/Cargo.toml index 252185fd0c66..cd05b5d50c09 100644 --- a/components/malloc_size_of/Cargo.toml +++ b/components/malloc_size_of/Cargo.toml @@ -12,7 +12,6 @@ path = "lib.rs" servo = [ "hyper", "hyper_serde", - "keyboard-types", "mozjs", "serde", "serde_bytes", @@ -26,13 +25,12 @@ servo = [ [dependencies] app_units = "0.7" -cssparser = "0.25" +cssparser = "0.24.0" euclid = "0.19" hashglobe = { path = "../hashglobe" } -hyper = { version = "0.12", optional = true } -hyper_serde = { version = "0.9", optional = true } -keyboard-types = {version = "0.4.2-servo", features = ["serde"], optional = true} -mozjs = { version = "0.9.3", optional = true } +hyper = { version = "0.10", optional = true } +hyper_serde = { version = "0.8", optional = true } +mozjs = { version = "0.9.0", optional = true } selectors = { path = "../selectors" } serde = { version = "1.0.27", optional = true } serde_bytes = { version = "0.10", optional = true } diff --git a/components/malloc_size_of/lib.rs b/components/malloc_size_of/lib.rs index 69dc48ce30d3..72b7f81595a7 100644 --- a/components/malloc_size_of/lib.rs +++ b/components/malloc_size_of/lib.rs @@ -52,8 +52,6 @@ extern crate hyper; #[cfg(feature = "servo")] extern crate hyper_serde; #[cfg(feature = "servo")] -extern crate keyboard_types; -#[cfg(feature = "servo")] extern crate mozjs as js; extern crate selectors; #[cfg(feature = "servo")] @@ -82,8 +80,8 @@ extern crate xml5ever; use serde_bytes::ByteBuf; use std::hash::{BuildHasher, Hash}; use std::mem::size_of; -use std::ops::Range; use std::ops::{Deref, DerefMut}; +use std::ops::Range; use std::os::raw::c_void; use void::Void; @@ -557,36 +555,6 @@ where } } -impl MallocShallowSizeOf for std::collections::BTreeMap -where - K: Eq + Hash, -{ - fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize { - if ops.has_malloc_enclosing_size_of() { - self.values() - .next() - .map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) }) - } else { - self.len() * (size_of::() + size_of::() + size_of::()) - } - } -} - -impl MallocSizeOf for std::collections::BTreeMap -where - K: Eq + Hash + MallocSizeOf, - V: MallocSizeOf, -{ - fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { - let mut n = self.shallow_size_of(ops); - for (k, v) in self.iter() { - n += k.size_of(ops); - n += v.size_of(ops); - } - n - } -} - impl MallocShallowSizeOf for hashglobe::hash_map::HashMap where K: Eq + Hash, @@ -947,6 +915,8 @@ malloc_size_of_is_0!(webrender_api::BorderRadius); #[cfg(feature = "webrender_api")] malloc_size_of_is_0!(webrender_api::BorderStyle); #[cfg(feature = "webrender_api")] +malloc_size_of_is_0!(webrender_api::BorderWidths); +#[cfg(feature = "webrender_api")] malloc_size_of_is_0!(webrender_api::BoxShadowClipMode); #[cfg(feature = "webrender_api")] malloc_size_of_is_0!(webrender_api::ClipAndScrollInfo); @@ -988,22 +958,51 @@ malloc_size_of_is_0!(webrender_api::StickyOffsetBounds); malloc_size_of_is_0!(webrender_api::TransformStyle); #[cfg(feature = "servo")] -impl MallocSizeOf for keyboard_types::Key { +impl MallocSizeOf for xml5ever::QualName { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { - match self { - keyboard_types::Key::Character(ref s) => s.size_of(ops), - _ => 0, - } + self.prefix.size_of(ops) + self.ns.size_of(ops) + self.local.size_of(ops) } } #[cfg(feature = "servo")] -malloc_size_of_is_0!(keyboard_types::Modifiers); +impl MallocSizeOf for hyper::header::Headers { + fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { + self.iter().fold(0, |acc, x| { + let name = x.name(); + let raw = self.get_raw(name); + acc + raw.size_of(ops) + }) + } +} #[cfg(feature = "servo")] -impl MallocSizeOf for xml5ever::QualName { +impl MallocSizeOf for hyper::header::ContentType { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { - self.prefix.size_of(ops) + self.ns.size_of(ops) + self.local.size_of(ops) + self.0.size_of(ops) + } +} + +#[cfg(feature = "servo")] +impl MallocSizeOf for hyper::mime::Mime { + fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { + self.0.size_of(ops) + self.1.size_of(ops) + self.2.size_of(ops) + } +} + +#[cfg(feature = "servo")] +impl MallocSizeOf for hyper::mime::Attr { + fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { + match *self { + hyper::mime::Attr::Ext(ref s) => s.size_of(ops), + _ => 0, + } + } +} + +#[cfg(feature = "servo")] +impl MallocSizeOf for hyper::mime::Value { + fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { + self.len() // Length of string value in bytes (not the char length of a string)! } } @@ -1034,9 +1033,12 @@ impl MallocSizeOf for servo_channel::Sender { } #[cfg(feature = "servo")] -impl MallocSizeOf for hyper::StatusCode { - fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize { - 0 +impl MallocSizeOf for hyper::status::StatusCode { + fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { + match *self { + hyper::status::StatusCode::Unregistered(u) => u.size_of(ops), + _ => 0, + } } } diff --git a/components/malloc_size_of_derive/lib.rs b/components/malloc_size_of_derive/lib.rs index dc0d34af88fe..59446131508f 100644 --- a/components/malloc_size_of_derive/lib.rs +++ b/components/malloc_size_of_derive/lib.rs @@ -88,8 +88,7 @@ fn malloc_size_of_derive(s: synstructure::Structure) -> quote::Tokens { fn test_struct() { let source = syn::parse_str( "struct Foo { bar: Bar, baz: T, #[ignore_malloc_size_of = \"\"] z: Arc }", - ) - .unwrap(); + ).unwrap(); let source = synstructure::Structure::new(&source); let expanded = malloc_size_of_derive(source).to_string(); diff --git a/components/metrics/Cargo.toml b/components/metrics/Cargo.toml index ebc90d5f5cd6..608d7ffaa0a2 100644 --- a/components/metrics/Cargo.toml +++ b/components/metrics/Cargo.toml @@ -3,7 +3,6 @@ name = "metrics" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/metrics/lib.rs b/components/metrics/lib.rs index e131822b69cf..f0411cb76273 100644 --- a/components/metrics/lib.rs +++ b/components/metrics/lib.rs @@ -2,16 +2,25 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate gfx_traits; +extern crate ipc_channel; #[macro_use] extern crate log; +extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; - -use gfx_traits::{DisplayList, Epoch}; +extern crate msg; +extern crate profile_traits; +extern crate script_traits; +extern crate servo_config; +extern crate servo_url; +extern crate time; + +use gfx_traits::{Epoch, DisplayList}; use ipc_channel::ipc::IpcSender; use msg::constellation_msg::PipelineId; +use profile_traits::time::{ProfilerChan, ProfilerCategory, send_profile_data}; use profile_traits::time::TimerMetadata; -use profile_traits::time::{send_profile_data, ProfilerCategory, ProfilerChan}; use script_traits::{ConstellationControlMsg, LayoutMsg, ProgressiveWebMetricType}; use servo_config::opts; use servo_url::ServoUrl; @@ -306,7 +315,7 @@ impl PaintTimeMetrics { &self, profiler_metadata_factory: &T, epoch: Epoch, - display_list: &dyn DisplayList, + display_list: &DisplayList, ) where T: ProfilerMetadataFactory, { diff --git a/components/msg/Cargo.toml b/components/msg/Cargo.toml index 815e8962a58c..86a9dac0aa9c 100644 --- a/components/msg/Cargo.toml +++ b/components/msg/Cargo.toml @@ -3,7 +3,6 @@ name = "msg" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -13,6 +12,7 @@ test = false doctest = false [dependencies] +bitflags = "1.0" malloc_size_of = { path = "../malloc_size_of" } malloc_size_of_derive = { path = "../malloc_size_of_derive" } serde = "1.0.60" diff --git a/components/msg/constellation_msg.rs b/components/msg/constellation_msg.rs index 449a7c3392e3..46697ad76452 100644 --- a/components/msg/constellation_msg.rs +++ b/components/msg/constellation_msg.rs @@ -8,6 +8,154 @@ use std::cell::Cell; use std::fmt; use std::num::NonZeroU32; +use webrender_api; + +#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub enum KeyState { + Pressed, + Released, + Repeated, +} + +//N.B. Based on the glutin key enum +#[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] +pub enum Key { + Space, + Apostrophe, + Comma, + Minus, + Period, + Slash, + Num0, + Num1, + Num2, + Num3, + Num4, + Num5, + Num6, + Num7, + Num8, + Num9, + Semicolon, + Equal, + A, + B, + C, + D, + E, + F, + G, + H, + I, + J, + K, + L, + M, + N, + O, + P, + Q, + R, + S, + T, + U, + V, + W, + X, + Y, + Z, + LeftBracket, + Backslash, + RightBracket, + GraveAccent, + World1, + World2, + + Escape, + Enter, + Tab, + Backspace, + Insert, + Delete, + Right, + Left, + Down, + Up, + PageUp, + PageDown, + Home, + End, + CapsLock, + ScrollLock, + NumLock, + PrintScreen, + Pause, + F1, + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, + F13, + F14, + F15, + F16, + F17, + F18, + F19, + F20, + F21, + F22, + F23, + F24, + F25, + Kp0, + Kp1, + Kp2, + Kp3, + Kp4, + Kp5, + Kp6, + Kp7, + Kp8, + Kp9, + KpDecimal, + KpDivide, + KpMultiply, + KpSubtract, + KpAdd, + KpEnter, + KpEqual, + LeftShift, + LeftControl, + LeftAlt, + LeftSuper, + RightShift, + RightControl, + RightAlt, + RightSuper, + Menu, + + NavigateBackward, + NavigateForward, +} + +bitflags! { + #[derive(Deserialize, Serialize)] + pub struct KeyModifiers: u8 { + const NONE = 0x00; + const SHIFT = 0x01; + const CONTROL = 0x02; + const ALT = 0x04; + const SUPER = 0x08; + } +} #[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] pub enum TraversalDirection { @@ -269,7 +417,7 @@ pub const TEST_BROWSING_CONTEXT_ID: BrowsingContextId = BrowsingContextId { // Used to specify the kind of input method editor appropriate to edit a field. // This is a subset of htmlinputelement::InputType because some variants of InputType // don't make sense in this context. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum InputMethodType { Color, Date, diff --git a/components/msg/lib.rs b/components/msg/lib.rs index d2490c142eba..ec9619bab056 100644 --- a/components/msg/lib.rs +++ b/components/msg/lib.rs @@ -4,11 +4,14 @@ #![deny(unsafe_code)] +#[macro_use] +extern crate bitflags; #[macro_use] extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; #[macro_use] extern crate serde; +extern crate webrender_api; pub mod constellation_msg; diff --git a/components/msg/tests/size_of.rs b/components/msg/tests/size_of.rs index 54995bcb6f72..62e2647ea615 100644 --- a/components/msg/tests/size_of.rs +++ b/components/msg/tests/size_of.rs @@ -4,6 +4,7 @@ #![cfg(target_pointer_width = "64")] +extern crate msg; #[macro_use] extern crate size_of_test; diff --git a/components/net/Cargo.toml b/components/net/Cargo.toml index ce05657d3712..aca08703baed 100644 --- a/components/net/Cargo.toml +++ b/components/net/Cargo.toml @@ -1,11 +1,8 @@ -cargo-features = ["rename-dependency"] - [package] name = "net" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false autotests = false # Inhibit lookup for tests/*.rs without [[test]] sections @@ -16,19 +13,15 @@ test = false doctest = false [dependencies] -base64 = "0.9" -brotli = "2.5" -bytes = "0.4" -cookie_rs = {package = "cookie", version = "0.11"} +base64 = "0.6" +brotli = "1.0.6" +cookie = "0.10" devtools_traits = {path = "../devtools_traits"} embedder_traits = { path = "../embedder_traits" } flate2 = "1" -headers-core = "0.0.1" -headers-ext = "0.0.3" -http = "0.1" -hyper = "0.12" -hyper_serde = "0.9" -hyper-openssl = "0.6" +hyper = "0.10" +hyper_serde = "0.8" +hyper-openssl = "0.2.2" immeta = "0.4" ipc-channel = "0.11" lazy_static = "1" @@ -36,12 +29,11 @@ log = "0.4" malloc_size_of = { path = "../malloc_size_of" } malloc_size_of_derive = { path = "../malloc_size_of_derive" } matches = "0.1" -mime = "0.3" -mime_guess = "2.0.0-alpha.6" +mime = "0.2.1" +mime_guess = "1.8.0" msg = {path = "../msg"} net_traits = {path = "../net_traits"} -openssl = "0.10" -pixels = {path = "../pixels"} +openssl = "0.9" profile_traits = {path = "../profile_traits"} serde = "1.0" serde_json = "1.0" @@ -50,19 +42,16 @@ servo_arc = {path = "../servo_arc"} servo_channel = {path = "../channel"} servo_config = {path = "../config"} servo_url = {path = "../url"} -tokio = "0.1" -tokio-timer = "0.2" threadpool = "1.0" time = "0.1.17" +unicase = "1.4.0" url = "1.2" uuid = {version = "0.6", features = ["v4"]} webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} ws = { version = "0.7", features = ["ssl"] } [dev-dependencies] -std_test_override = { path = "../std_test_override" } -futures = "0.1" -tokio-openssl = "0.2" +embedder_traits = { path = "../embedder_traits", features = ["tests"] } [[test]] name = "main" diff --git a/components/net/blob_loader.rs b/components/net/blob_loader.rs index 2afed16ad7f3..1fe05cc1c20b 100644 --- a/components/net/blob_loader.rs +++ b/components/net/blob_loader.rs @@ -2,16 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::filemanager_thread::FileManager; -use headers_core::HeaderMapExt; -use headers_ext::{ContentLength, ContentType}; -use http::header::{self, HeaderValue}; -use http::HeaderMap; +use filemanager_thread::FileManager; +use hyper::header::{Charset, ContentLength, ContentType, Headers}; +use hyper::header::{ContentDisposition, DispositionParam, DispositionType}; use ipc_channel::ipc; -use mime::{self, Mime}; +use mime::{Attr, Mime}; +use net_traits::NetworkError; use net_traits::blob_url_store::parse_blob_url; use net_traits::filemanager_thread::ReadFileProgress; -use net_traits::{http_percent_encode, NetworkError}; use servo_url::ServoUrl; // TODO: Check on GET @@ -19,16 +17,16 @@ use servo_url::ServoUrl; /// https://fetch.spec.whatwg.org/#concept-basic-fetch (partial) // TODO: make async. -pub fn load_blob_sync( - url: ServoUrl, - filemanager: FileManager, -) -> Result<(HeaderMap, Vec), NetworkError> { +pub fn load_blob_sync + (url: ServoUrl, + filemanager: FileManager) + -> Result<(Headers, Vec), NetworkError> { let (id, origin) = match parse_blob_url(&url) { Ok((id, origin)) => (id, origin), Err(()) => { let e = format!("Invalid blob URL format {:?}", url); return Err(NetworkError::Internal(e)); - }, + } }; let (sender, receiver) = ipc::channel().unwrap(); @@ -38,71 +36,49 @@ pub fn load_blob_sync( let blob_buf = match receiver.recv().unwrap() { Ok(ReadFileProgress::Meta(blob_buf)) => blob_buf, Ok(_) => { - return Err(NetworkError::Internal( - "Invalid filemanager reply".to_string(), - )); - }, + return Err(NetworkError::Internal("Invalid filemanager reply".to_string())); + } Err(e) => { return Err(NetworkError::Internal(format!("{:?}", e))); - }, + } }; - let content_type: Mime = blob_buf.type_string.parse().unwrap_or(mime::TEXT_PLAIN); - let charset = content_type.get_param(mime::CHARSET); + let content_type: Mime = blob_buf.type_string.parse().unwrap_or(mime!(Text / Plain)); + let charset = content_type.get_param(Attr::Charset); - let mut headers = HeaderMap::new(); + let mut headers = Headers::new(); if let Some(name) = blob_buf.filename { - let charset = charset - .map(|c| c.as_ref().into()) - .unwrap_or("us-ascii".to_owned()); - // TODO(eijebong): Replace this once the typed header is there - headers.insert( - header::CONTENT_DISPOSITION, - HeaderValue::from_bytes( - format!( - "inline; {}", - if charset.to_lowercase() == "utf-8" { - format!( - "filename=\"{}\"", - String::from_utf8(name.as_bytes().into()).unwrap() - ) - } else { - format!( - "filename*=\"{}\"''{}", - charset, - http_percent_encode(name.as_bytes()) - ) - } - ) - .as_bytes(), - ) - .unwrap(), - ); + let charset = charset.and_then(|c| c.as_str().parse().ok()); + headers.set(ContentDisposition { + disposition: DispositionType::Inline, + parameters: vec![ + DispositionParam::Filename(charset.unwrap_or(Charset::Us_Ascii), + None, name.as_bytes().to_vec()) + ] + }); } // Basic fetch, Step 4. - headers.typed_insert(ContentLength(blob_buf.size as u64)); + headers.set(ContentLength(blob_buf.size as u64)); // Basic fetch, Step 5. - headers.typed_insert(ContentType::from(content_type.clone())); + headers.set(ContentType(content_type.clone())); let mut bytes = blob_buf.bytes; loop { match receiver.recv().unwrap() { Ok(ReadFileProgress::Partial(ref mut new_bytes)) => { bytes.append(new_bytes); - }, + } Ok(ReadFileProgress::EOF) => { return Ok((headers, bytes)); - }, + } Ok(_) => { - return Err(NetworkError::Internal( - "Invalid filemanager reply".to_string(), - )); - }, + return Err(NetworkError::Internal("Invalid filemanager reply".to_string())); + } Err(e) => { return Err(NetworkError::Internal(format!("{:?}", e))); - }, + } } } } diff --git a/components/net/connector.rs b/components/net/connector.rs index 452b0db703d8..03ee7e5459d3 100644 --- a/components/net/connector.rs +++ b/components/net/connector.rs @@ -2,203 +2,94 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::hosts::replace_host; -use crate::http_loader::Decoder; -use flate2::read::GzDecoder; -use hyper::body::Payload; -use hyper::client::connect::{Connect, Destination}; -use hyper::client::HttpConnector as HyperHttpConnector; -use hyper::rt::Future; -use hyper::{Body, Client}; -use hyper_openssl::HttpsConnector; -use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslOptions}; +use hosts::replace_host; +use hyper::client::Pool; +use hyper::error::{Result as HyperResult, Error as HyperError}; +use hyper::net::{NetworkConnector, HttpsStream, HttpStream, SslClient}; +use hyper_openssl::OpensslClient; +use openssl::ssl::{SSL_OP_NO_COMPRESSION, SSL_OP_NO_SSLV2, SSL_OP_NO_SSLV3}; +use openssl::ssl::{SslConnector, SslConnectorBuilder, SslMethod}; use openssl::x509; -use std::io::{Cursor, Read}; -use tokio::prelude::future::Executor; -use tokio::prelude::{Async, Stream}; +use std::io; +use std::net::TcpStream; -pub const BUF_SIZE: usize = 32768; - -pub struct HttpConnector { - inner: HyperHttpConnector, -} - -impl HttpConnector { - fn new() -> HttpConnector { - let mut inner = HyperHttpConnector::new(4); - inner.enforce_http(false); - inner.set_happy_eyeballs_timeout(None); - HttpConnector { inner } - } +pub struct HttpsConnector { + ssl: OpensslClient, } -impl Connect for HttpConnector { - type Transport = ::Transport; - type Error = ::Error; - type Future = ::Future; - - fn connect(&self, dest: Destination) -> Self::Future { - // Perform host replacement when making the actual TCP connection. - let mut new_dest = dest.clone(); - let addr = replace_host(dest.host()); - new_dest.set_host(&*addr).unwrap(); - self.inner.connect(new_dest) +impl HttpsConnector { + fn new(ssl: OpensslClient) -> HttpsConnector { + HttpsConnector { + ssl: ssl, + } } } -pub type Connector = HttpsConnector; -pub struct WrappedBody { - pub body: Body, - pub decoder: Decoder, -} +impl NetworkConnector for HttpsConnector { + type Stream = HttpsStream<::Stream>; -impl WrappedBody { - pub fn new(body: Body) -> Self { - Self::new_with_decoder(body, Decoder::Plain) - } + fn connect(&self, host: &str, port: u16, scheme: &str) -> HyperResult { + if scheme != "http" && scheme != "https" { + return Err(HyperError::Io(io::Error::new(io::ErrorKind::InvalidInput, + "Invalid scheme for Http"))); + } - pub fn new_with_decoder(body: Body, decoder: Decoder) -> Self { - WrappedBody { body, decoder } - } -} + // Perform host replacement when making the actual TCP connection. + let addr = &(&*replace_host(host), port); + let stream = HttpStream(TcpStream::connect(addr)?); -impl Payload for WrappedBody { - type Data = ::Data; - type Error = ::Error; - fn poll_data(&mut self) -> Result>, Self::Error> { - self.body.poll_data() + if scheme == "http" { + Ok(HttpsStream::Http(stream)) + } else { + // Do not perform host replacement on the host that is used + // for verifying any SSL certificate encountered. + self.ssl.wrap_client(stream, host).map(HttpsStream::Https) + } } } -impl Stream for WrappedBody { - type Item = ::Item; - type Error = ::Error; - fn poll(&mut self) -> Result>, Self::Error> { - self.body.poll().map(|res| { - res.map(|maybe_chunk| { - if let Some(chunk) = maybe_chunk { - match self.decoder { - Decoder::Plain => Some(chunk), - Decoder::Gzip(Some(ref mut decoder)) => { - let mut buf = vec![0; BUF_SIZE]; - decoder.get_mut().get_mut().extend(chunk.as_ref()); - let len = decoder.read(&mut buf).ok()?; - buf.truncate(len); - Some(buf.into()) - }, - Decoder::Gzip(None) => { - let mut buf = vec![0; BUF_SIZE]; - let mut decoder = GzDecoder::new(Cursor::new(chunk.into_bytes())); - let len = decoder.read(&mut buf).ok()?; - buf.truncate(len); - self.decoder = Decoder::Gzip(Some(decoder)); - Some(buf.into()) - }, - Decoder::Deflate(ref mut decoder) => { - let mut buf = vec![0; BUF_SIZE]; - decoder.get_mut().get_mut().extend(chunk.as_ref()); - let len = decoder.read(&mut buf).ok()?; - buf.truncate(len); - Some(buf.into()) - }, - Decoder::Brotli(ref mut decoder) => { - let mut buf = vec![0; BUF_SIZE]; - decoder.get_mut().get_mut().extend(chunk.as_ref()); - let len = decoder.read(&mut buf).ok()?; - buf.truncate(len); - Some(buf.into()) - }, - } - } else { - // Hyper is done downloading but we still have uncompressed data - match self.decoder { - Decoder::Gzip(Some(ref mut decoder)) => { - let mut buf = vec![0; BUF_SIZE]; - let len = decoder.read(&mut buf).ok()?; - if len == 0 { - return None; - } - buf.truncate(len); - Some(buf.into()) - }, - Decoder::Deflate(ref mut decoder) => { - let mut buf = vec![0; BUF_SIZE]; - let len = decoder.read(&mut buf).ok()?; - if len == 0 { - return None; - } - buf.truncate(len); - Some(buf.into()) - }, - Decoder::Brotli(ref mut decoder) => { - let mut buf = vec![0; BUF_SIZE]; - let len = decoder.read(&mut buf).ok()?; - if len == 0 { - return None; - } - buf.truncate(len); - Some(buf.into()) - }, - _ => None, - } - } - }) - }) - } -} +pub type Connector = HttpsConnector; -pub fn create_ssl_connector_builder(certs: &str) -> SslConnectorBuilder { +pub fn create_ssl_connector(certs: &str) -> SslConnector { // certs include multiple certificates. We could add all of them at once, // but if any of them were already added, openssl would fail to insert all // of them. let mut certs = certs; - let mut ssl_connector_builder = SslConnector::builder(SslMethod::tls()).unwrap(); + let mut ssl_connector_builder = SslConnectorBuilder::new(SslMethod::tls()).unwrap(); loop { let token = "-----END CERTIFICATE-----"; if let Some(index) = certs.find(token) { let (cert, rest) = certs.split_at(index + token.len()); certs = rest; let cert = x509::X509::from_pem(cert.as_bytes()).unwrap(); - ssl_connector_builder - .cert_store_mut() - .add_cert(cert) - .or_else(|e| { - let v: Option> = e.errors().iter().nth(0).map(|e| e.reason()); - if v == Some(Some("cert already in hash table")) { - warn!("Cert already in hash table. Ignoring."); - // Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the - // certificate is already in the store. - Ok(()) - } else { - Err(e) - } - }) - .expect("could not set CA file"); + ssl_connector_builder.cert_store_mut().add_cert(cert).or_else(|e| { + let v: Option> = e.errors().iter().nth(0).map(|e| e.reason()); + if v == Some(Some("cert already in hash table")) { + warn!("Cert already in hash table. Ignoring."); + // Ignore error X509_R_CERT_ALREADY_IN_HASH_TABLE which means the + // certificate is already in the store. + Ok(()) + } else { + Err(e) + } + }).expect("could not set CA file"); } else { break; } } - ssl_connector_builder - .set_cipher_list(DEFAULT_CIPHERS) - .expect("could not set ciphers"); - ssl_connector_builder - .set_options(SslOptions::NO_SSLV2 | SslOptions::NO_SSLV3 | SslOptions::NO_COMPRESSION); - ssl_connector_builder + ssl_connector_builder.set_cipher_list(DEFAULT_CIPHERS).expect("could not set ciphers"); + ssl_connector_builder.set_options(SSL_OP_NO_SSLV2 | SSL_OP_NO_SSLV3 | SSL_OP_NO_COMPRESSION); + ssl_connector_builder.build() +} + +pub fn create_ssl_client(certs: &str) -> OpensslClient { + let ssl_connector = create_ssl_connector(certs); + OpensslClient::from(ssl_connector) } -pub fn create_http_client( - ssl_connector_builder: SslConnectorBuilder, - executor: E, -) -> Client -where - E: Executor + Send + 'static>> + Sync + Send + 'static, -{ - let connector = - HttpsConnector::with_connector(HttpConnector::new(), ssl_connector_builder).unwrap(); - Client::builder() - .http1_title_case_headers(true) - .executor(executor) - .build(connector) +pub fn create_http_connector(ssl_client: OpensslClient) -> Pool { + let https_connector = HttpsConnector::new(ssl_client); + Pool::with_connector(Default::default(), https_connector) } // The basic logic here is to prefer ciphers with ECDSA certificates, Forward diff --git a/components/net/cookie.rs b/components/net/cookie.rs index adfd5e6147b6..e8e7be6733dd 100644 --- a/components/net/cookie.rs +++ b/components/net/cookie.rs @@ -5,45 +5,37 @@ //! Implementation of cookie creation and matching as specified by //! http://tools.ietf.org/html/rfc6265 +use cookie_rs; use hyper_serde::{self, Serde}; -use net_traits::pub_domains::is_pub_domain; use net_traits::CookieSource; +use net_traits::pub_domains::is_pub_domain; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::net::{Ipv4Addr, Ipv6Addr}; -use time::{at, now, Duration, Tm}; +use time::{Tm, now, at, Duration}; /// A stored cookie that wraps the definition in cookie-rs. This is used to implement /// various behaviours defined in the spec that rely on an associated request URL, /// which cookie-rs and hyper's header parsing do not support. #[derive(Clone, Debug, Deserialize, Serialize)] pub struct Cookie { - #[serde( - deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize" - )] + #[serde(deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize")] pub cookie: cookie_rs::Cookie<'static>, pub host_only: bool, pub persistent: bool, - #[serde( - deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize" - )] + #[serde(deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize")] pub creation_time: Tm, - #[serde( - deserialize_with = "hyper_serde::deserialize", - serialize_with = "hyper_serde::serialize" - )] + #[serde(deserialize_with = "hyper_serde::deserialize", + serialize_with = "hyper_serde::serialize")] pub last_access: Tm, pub expiry_time: Option>, } impl Cookie { - pub fn from_cookie_string( - cookie_str: String, - request: &ServoUrl, - source: CookieSource, - ) -> Option { + pub fn from_cookie_string(cookie_str: String, request: &ServoUrl, + source: CookieSource) -> Option { cookie_rs::Cookie::parse(cookie_str) .ok() .map(|cookie| Cookie::new_wrapped(cookie, request, source)) @@ -51,21 +43,15 @@ impl Cookie { } /// - pub fn new_wrapped( - mut cookie: cookie_rs::Cookie<'static>, - request: &ServoUrl, - source: CookieSource, - ) -> Option { + pub fn new_wrapped(mut cookie: cookie_rs::Cookie<'static>, request: &ServoUrl, source: CookieSource) + -> Option { // Step 3 let (persistent, expiry_time) = match (cookie.max_age(), cookie.expires()) { - (Some(max_age), _) => ( - true, - Some(at( - now().to_timespec() + Duration::seconds(max_age.num_seconds()) - )), - ), + (Some(max_age), _) => { + (true, Some(at(now().to_timespec() + Duration::seconds(max_age.num_seconds())))) + } (_, Some(expires)) => (true, Some(expires)), - _ => (false, None), + _ => (false, None) }; let url_host = request.host_str().unwrap_or("").to_owned(); @@ -78,7 +64,7 @@ impl Cookie { if domain == url_host { domain = "".to_string(); } else { - return None; + return None } } @@ -97,34 +83,32 @@ impl Cookie { // Step 7 let mut has_path_specified = true; - let mut path = cookie - .path() - .unwrap_or_else(|| { - has_path_specified = false; - "" - }) - .to_owned(); + let mut path = cookie.path().unwrap_or_else(|| { + has_path_specified = false; + "" + }).to_owned(); if path.chars().next() != Some('/') { path = Cookie::default_path(&request.path().to_owned()).to_string(); } cookie.set_path(path); + // Step 10 - if cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP { + if cookie.http_only() && source == CookieSource::NonHTTP { return None; } // https://tools.ietf.org/html/draft-west-cookie-prefixes-04#section-4 // Step 1 of cookie prefixes if (cookie.name().starts_with("__Secure-") || cookie.name().starts_with("__Host-")) && - !(cookie.secure().unwrap_or(false) && request.is_secure_scheme()) + !(cookie.secure() && request.is_secure_scheme()) { return None; } // Step 2 of cookie prefixes if cookie.name().starts_with("__Host-") && - !(host_only && has_path_specified && cookie.path().unwrap() == "/") + !(host_only && has_path_specified && cookie.path().unwrap() == "/") { return None; } @@ -168,16 +152,16 @@ impl Cookie { // The cookie-path and the request-path are identical. request_path == cookie_path || - (request_path.starts_with(cookie_path) && - ( - // The cookie-path is a prefix of the request-path, and the last - // character of the cookie-path is %x2F ("/"). - cookie_path.ends_with("/") || + + (request_path.starts_with(cookie_path) && ( + // The cookie-path is a prefix of the request-path, and the last + // character of the cookie-path is %x2F ("/"). + cookie_path.ends_with("/") || // The cookie-path is a prefix of the request-path, and the first // character of the request-path that is not included in the cookie- // path is a %x2F ("/") character. request_path[cookie_path.len()..].starts_with("/") - )) + )) } // http://tools.ietf.org/html/rfc6265#section-5.1.3 @@ -186,10 +170,10 @@ impl Cookie { let domain_string = &domain_string.to_lowercase(); string == domain_string || - (string.ends_with(domain_string) && - string.as_bytes()[string.len() - domain_string.len() - 1] == b'.' && - string.parse::().is_err() && - string.parse::().is_err()) + (string.ends_with(domain_string) && + string.as_bytes()[string.len()-domain_string.len()-1] == b'.' && + string.parse::().is_err() && + string.parse::().is_err()) } // http://tools.ietf.org/html/rfc6265#section-5.4 step 1 @@ -213,10 +197,10 @@ impl Cookie { } } - if self.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() { + if self.cookie.secure() && !url.is_secure_scheme() { return false; } - if self.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP { + if self.cookie.http_only() && source == CookieSource::NonHTTP { return false; } diff --git a/components/net/cookie_storage.rs b/components/net/cookie_storage.rs index a0b7484f0c56..4dc7075a9fd0 100644 --- a/components/net/cookie_storage.rs +++ b/components/net/cookie_storage.rs @@ -5,13 +5,16 @@ //! Implementation of cookie storage as specified in //! http://tools.ietf.org/html/rfc6265 -use crate::cookie::Cookie; -use net_traits::pub_domains::reg_suffix; +use cookie::Cookie; +use cookie_rs; use net_traits::CookieSource; +use net_traits::pub_domains::reg_suffix; use servo_url::ServoUrl; use std::cmp::Ordering; use std::collections::HashMap; -use time::{self, Tm}; +use time::Tm; + +extern crate time; #[derive(Clone, Debug, Deserialize, Serialize)] pub struct CookieStorage { @@ -30,17 +33,12 @@ impl CookieStorage { } // http://tools.ietf.org/html/rfc6265#section-5.3 - pub fn remove( - &mut self, - cookie: &Cookie, - url: &ServoUrl, - source: CookieSource, - ) -> Result, ()> { + pub fn remove(&mut self, cookie: &Cookie, url: &ServoUrl, source: CookieSource) -> Result, ()> { let domain = reg_host(cookie.cookie.domain().as_ref().unwrap_or(&"")); let cookies = self.cookies_map.entry(domain).or_insert(vec![]); // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 2 - if !cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() { + if !cookie.cookie.secure() && !url.is_secure_scheme() { let new_domain = cookie.cookie.domain().as_ref().unwrap().to_owned(); let new_path = cookie.cookie.path().as_ref().unwrap().to_owned(); @@ -49,10 +47,10 @@ impl CookieStorage { let existing_path = c.cookie.path().as_ref().unwrap().to_owned(); c.cookie.name() == cookie.cookie.name() && - c.cookie.secure().unwrap_or(false) && - (Cookie::domain_match(new_domain, existing_domain) || - Cookie::domain_match(existing_domain, new_domain)) && - Cookie::path_match(new_path, existing_path) + c.cookie.secure() && + (Cookie::domain_match(new_domain, existing_domain) || + Cookie::domain_match(existing_domain, new_domain)) && + Cookie::path_match(new_path, existing_path) }); if any_overlapping { @@ -63,8 +61,8 @@ impl CookieStorage { // Step 11.1 let position = cookies.iter().position(|c| { c.cookie.domain() == cookie.cookie.domain() && - c.cookie.path() == cookie.cookie.path() && - c.cookie.name() == cookie.cookie.name() + c.cookie.path() == cookie.cookie.path() && + c.cookie.name() == cookie.cookie.name() }); if let Some(ind) = position { @@ -72,7 +70,7 @@ impl CookieStorage { let c = cookies.remove(ind); // http://tools.ietf.org/html/rfc6265#section-5.3 step 11.2 - if c.cookie.http_only().unwrap_or(false) && source == CookieSource::NonHTTP { + if c.cookie.http_only() && source == CookieSource::NonHTTP { // Undo the removal. cookies.push(c); Err(()) @@ -87,7 +85,7 @@ impl CookieStorage { // http://tools.ietf.org/html/rfc6265#section-5.3 pub fn push(&mut self, mut cookie: Cookie, url: &ServoUrl, source: CookieSource) { // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt Step 1 - if cookie.cookie.secure().unwrap_or(false) && !url.is_secure_scheme() { + if cookie.cookie.secure() && !url.is_secure_scheme() { return; } @@ -113,9 +111,7 @@ impl CookieStorage { let new_len = cookies.len(); // https://www.ietf.org/id/draft-ietf-httpbis-cookie-alone-01.txt - if new_len == old_len && - !evict_one_cookie(cookie.cookie.secure().unwrap_or(false), cookies) - { + if new_len == old_len && !evict_one_cookie(cookie.cookie.secure(), cookies) { return; } } @@ -130,7 +126,7 @@ impl CookieStorage { let a_creation_time = a.creation_time.to_timespec(); let b_creation_time = b.creation_time.to_timespec(); a_creation_time.cmp(&b_creation_time) - }, + } // Ensure that longer paths are sorted earlier than shorter paths Ordering::Greater => Ordering::Less, Ordering::Less => Ordering::Greater, @@ -140,17 +136,13 @@ impl CookieStorage { // http://tools.ietf.org/html/rfc6265#section-5.4 pub fn cookies_for_url(&mut self, url: &ServoUrl, source: CookieSource) -> Option { let filterer = |c: &&mut Cookie| -> bool { - info!( - " === SENT COOKIE : {} {} {:?} {:?}", - c.cookie.name(), - c.cookie.value(), - c.cookie.domain(), - c.cookie.path() - ); - info!( - " === SENT COOKIE RESULT {}", - c.appropriate_for_url(url, source) - ); + info!(" === SENT COOKIE : {} {} {:?} {:?}", + c.cookie.name(), + c.cookie.value(), + c.cookie.domain(), + c.cookie.path()); + info!(" === SENT COOKIE RESULT {}", + c.appropriate_for_url(url, source)); // Step 1 c.appropriate_for_url(url, source) }; @@ -169,9 +161,7 @@ impl CookieStorage { (match acc.len() { 0 => acc, _ => acc + "; ", - }) + &c.cookie.name() + - "=" + - &c.cookie.value() + }) + &c.cookie.name() + "=" + &c.cookie.value() }; let result = url_cookies.iter_mut().fold("".to_owned(), reducer); @@ -182,21 +172,17 @@ impl CookieStorage { } } - pub fn cookies_data_for_url<'a>( - &'a mut self, - url: &'a ServoUrl, - source: CookieSource, - ) -> impl Iterator> + 'a { + pub fn cookies_data_for_url<'a>(&'a mut self, + url: &'a ServoUrl, + source: CookieSource) + -> impl Iterator> + 'a { let domain = reg_host(url.host_str().unwrap_or("")); let cookies = self.cookies_map.entry(domain).or_insert(vec![]); - cookies - .iter_mut() - .filter(move |c| c.appropriate_for_url(url, source)) - .map(|c| { - c.touch(); - c.cookie.clone() - }) + cookies.iter_mut().filter(move |c| c.appropriate_for_url(url, source)).map(|c| { + c.touch(); + c.cookie.clone() + }) } } @@ -233,10 +219,8 @@ fn evict_one_cookie(is_secure_cookie: bool, cookies: &mut Vec) -> bool { fn get_oldest_accessed(is_secure_cookie: bool, cookies: &mut Vec) -> Option<(usize, Tm)> { let mut oldest_accessed: Option<(usize, Tm)> = None; for (i, c) in cookies.iter().enumerate() { - if (c.cookie.secure().unwrap_or(false) == is_secure_cookie) && oldest_accessed - .as_ref() - .map_or(true, |a| c.last_access < a.1) - { + if (c.cookie.secure() == is_secure_cookie) && + oldest_accessed.as_ref().map_or(true, |a| c.last_access < a.1) { oldest_accessed = Some((i, c.last_access)); } } diff --git a/components/net/data_loader.rs b/components/net/data_loader.rs index 9f0e1627ea3f..b95a2ab34123 100644 --- a/components/net/data_loader.rs +++ b/components/net/data_loader.rs @@ -3,10 +3,10 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use base64; -use mime::Mime; +use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use servo_url::ServoUrl; -use url::percent_encoding::percent_decode; use url::Position; +use url::percent_encoding::percent_decode; pub enum DecodeError { InvalidDataUri, @@ -18,9 +18,7 @@ pub type DecodeData = (Mime, Vec); pub fn decode(url: &ServoUrl) -> Result { assert_eq!(url.scheme(), "data"); // Split out content type and data. - let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery] - .splitn(2, ',') - .collect(); + let parts: Vec<&str> = url[Position::BeforePath..Position::AfterQuery].splitn(2, ',').collect(); if parts.len() != 2 { return Err(DecodeError::InvalidDataUri); } @@ -38,18 +36,16 @@ pub fn decode(url: &ServoUrl) -> Result { ct_str.to_owned() }; - let content_type = ct_str - .parse() - .unwrap_or_else(|_| "text/plain; charset=US-ASCII".parse().unwrap()); + let content_type = ct_str.parse().unwrap_or_else(|_| { + Mime(TopLevel::Text, SubLevel::Plain, + vec![(Attr::Charset, Value::Ext("US-ASCII".to_owned()))]) + }); let mut bytes = percent_decode(parts[1].as_bytes()).collect::>(); if is_base64 { // FIXME(#2909): It’s unclear what to do with non-alphabet characters, // but Acid 3 apparently depends on spaces being ignored. - bytes = bytes - .into_iter() - .filter(|&b| b != b' ') - .collect::>(); + bytes = bytes.into_iter().filter(|&b| b != b' ').collect::>(); match base64::decode(&bytes) { Err(..) => return Err(DecodeError::NonBase64DataUri), Ok(data) => bytes = data, diff --git a/components/net/fetch/cors_cache.rs b/components/net/fetch/cors_cache.rs index f23af1594552..8962dd2c9985 100644 --- a/components/net/fetch/cors_cache.rs +++ b/components/net/fetch/cors_cache.rs @@ -9,8 +9,7 @@ //! This library will eventually become the core of the Fetch crate //! with CORSRequest being expanded into FetchRequest (etc) -use http::header::HeaderName; -use hyper::Method; +use hyper::method::Method; use net_traits::request::{CredentialsMode, Origin, Request}; use servo_url::ServoUrl; use time::{self, Timespec}; @@ -20,22 +19,22 @@ use time::{self, Timespec}; /// Each entry might pertain to a header or method #[derive(Clone, Debug)] pub enum HeaderOrMethod { - HeaderData(HeaderName), - MethodData(Method), + HeaderData(String), + MethodData(Method) } impl HeaderOrMethod { - fn match_header(&self, header_name: &HeaderName) -> bool { + fn match_header(&self, header_name: &str) -> bool { match *self { - HeaderOrMethod::HeaderData(ref n) => n == header_name, - _ => false, + HeaderOrMethod::HeaderData(ref s) => (&**s).eq_ignore_ascii_case(header_name), + _ => false } } fn match_method(&self, method: &Method) -> bool { match *self { HeaderOrMethod::MethodData(ref m) => m == method, - _ => false, + _ => false } } } @@ -48,24 +47,19 @@ pub struct CorsCacheEntry { pub max_age: u32, pub credentials: bool, pub header_or_method: HeaderOrMethod, - created: Timespec, + created: Timespec } impl CorsCacheEntry { - fn new( - origin: Origin, - url: ServoUrl, - max_age: u32, - credentials: bool, - header_or_method: HeaderOrMethod, - ) -> CorsCacheEntry { + fn new(origin: Origin, url: ServoUrl, max_age: u32, credentials: bool, + header_or_method: HeaderOrMethod) -> CorsCacheEntry { CorsCacheEntry { origin: origin, url: url, max_age: max_age, credentials: credentials, header_or_method: header_or_method, - created: time::now().to_timespec(), + created: time::now().to_timespec() } } } @@ -85,36 +79,25 @@ impl CorsCache { CorsCache(vec![]) } - fn find_entry_by_header<'a>( - &'a mut self, - request: &Request, - header_name: &HeaderName, - ) -> Option<&'a mut CorsCacheEntry> { + fn find_entry_by_header<'a>(&'a mut self, request: &Request, + header_name: &str) -> Option<&'a mut CorsCacheEntry> { self.cleanup(); - self.0 - .iter_mut() - .find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) + self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_header(header_name)) } - fn find_entry_by_method<'a>( - &'a mut self, - request: &Request, - method: Method, - ) -> Option<&'a mut CorsCacheEntry> { + fn find_entry_by_method<'a>(&'a mut self, request: &Request, + method: Method) -> Option<&'a mut CorsCacheEntry> { // we can take the method from CorSRequest itself self.cleanup(); - self.0 - .iter_mut() - .find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) + self.0.iter_mut().find(|e| match_headers(e, request) && e.header_or_method.match_method(&method)) } /// [Clear the cache](https://fetch.spec.whatwg.org/#concept-cache-clear) pub fn clear(&mut self, request: &Request) { let CorsCache(buf) = self.clone(); - let new_buf: Vec = buf - .into_iter() - .filter(|e| e.origin == request.origin && request.current_url() == e.url) - .collect(); + let new_buf: Vec = + buf.into_iter().filter(|e| e.origin == request.origin && + request.current_url() == e.url).collect(); *self = CorsCache(new_buf); } @@ -122,16 +105,15 @@ impl CorsCache { pub fn cleanup(&mut self) { let CorsCache(buf) = self.clone(); let now = time::now().to_timespec(); - let new_buf: Vec = buf - .into_iter() - .filter(|e| now.sec < e.created.sec + e.max_age as i64) - .collect(); + let new_buf: Vec = buf.into_iter() + .filter(|e| now.sec < e.created.sec + e.max_age as i64) + .collect(); *self = CorsCache(new_buf); } /// Returns true if an entry with a /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found - pub fn match_header(&mut self, request: &Request, header_name: &HeaderName) -> bool { + pub fn match_header(&mut self, request: &Request, header_name: &str) -> bool { self.find_entry_by_header(&request, header_name).is_some() } @@ -139,27 +121,16 @@ impl CorsCache { /// [matching header](https://fetch.spec.whatwg.org/#concept-cache-match-header) is found. /// /// If not, it will insert an equivalent entry - pub fn match_header_and_update( - &mut self, - request: &Request, - header_name: &HeaderName, - new_max_age: u32, - ) -> bool { - match self - .find_entry_by_header(&request, header_name) - .map(|e| e.max_age = new_max_age) - { + pub fn match_header_and_update(&mut self, request: &Request, + header_name: &str, new_max_age: u32) -> bool { + match self.find_entry_by_header(&request, header_name).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { - self.insert(CorsCacheEntry::new( - request.origin.clone(), - request.current_url(), - new_max_age, - request.credentials_mode == CredentialsMode::Include, - HeaderOrMethod::HeaderData(header_name.clone()), - )); + self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, + request.credentials_mode == CredentialsMode::Include, + HeaderOrMethod::HeaderData(header_name.to_owned()))); false - }, + } } } @@ -173,27 +144,15 @@ impl CorsCache { /// [a matching method](https://fetch.spec.whatwg.org/#concept-cache-match-method) is found. /// /// If not, it will insert an equivalent entry - pub fn match_method_and_update( - &mut self, - request: &Request, - method: Method, - new_max_age: u32, - ) -> bool { - match self - .find_entry_by_method(&request, method.clone()) - .map(|e| e.max_age = new_max_age) - { + pub fn match_method_and_update(&mut self, request: &Request, method: Method, new_max_age: u32) -> bool { + match self.find_entry_by_method(&request, method.clone()).map(|e| e.max_age = new_max_age) { Some(_) => true, None => { - self.insert(CorsCacheEntry::new( - request.origin.clone(), - request.current_url(), - new_max_age, - request.credentials_mode == CredentialsMode::Include, - HeaderOrMethod::MethodData(method), - )); + self.insert(CorsCacheEntry::new(request.origin.clone(), request.current_url(), new_max_age, + request.credentials_mode == CredentialsMode::Include, + HeaderOrMethod::MethodData(method))); false - }, + } } } diff --git a/components/net/fetch/methods.rs b/components/net/fetch/methods.rs index 499070c04d2f..931a6e778e7e 100644 --- a/components/net/fetch/methods.rs +++ b/components/net/fetch/methods.rs @@ -2,46 +2,41 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::blob_loader::load_blob_sync; -use crate::data_loader::decode; -use crate::fetch::cors_cache::CorsCache; -use crate::filemanager_thread::FileManager; -use crate::http_loader::{determine_request_referrer, http_fetch, HttpState}; -use crate::http_loader::{set_default_accept, set_default_accept_language}; -use crate::subresource_integrity::is_response_integrity_valid; +use blob_loader::load_blob_sync; +use data_loader::decode; use devtools_traits::DevtoolsControlMsg; -use headers_core::HeaderMapExt; -use headers_ext::{AccessControlExposeHeaders, ContentType, Range}; -use http::header::{self, HeaderMap, HeaderName, HeaderValue}; -use hyper::Method; -use hyper::StatusCode; +use fetch::cors_cache::CorsCache; +use filemanager_thread::FileManager; +use http_loader::{HttpState, determine_request_referrer, http_fetch}; +use http_loader::{set_default_accept, set_default_accept_language}; +use hyper::{Error, Result as HyperResult}; +use hyper::header::{Accept, AcceptLanguage, AccessControlExposeHeaders, ContentLanguage, ContentType}; +use hyper::header::{Header, HeaderFormat, HeaderView, Headers, Referer as RefererHeader}; +use hyper::method::Method; +use hyper::mime::{Mime, SubLevel, TopLevel}; +use hyper::status::StatusCode; use ipc_channel::ipc::IpcReceiver; -use mime::{self, Mime}; use mime_guess::guess_mime_type; +use net_traits::{FetchTaskTarget, NetworkError, ReferrerPolicy}; use net_traits::request::{CredentialsMode, Destination, Referrer, Request, RequestMode}; -use net_traits::request::{Origin, ResponseTainting, Window}; +use net_traits::request::{ResponseTainting, Origin, Window}; use net_traits::response::{Response, ResponseBody, ResponseType}; -use net_traits::{FetchTaskTarget, NetworkError, ReferrerPolicy}; -use servo_channel::{channel, Receiver, Sender}; +use servo_channel::{channel, Sender, Receiver}; use servo_url::ServoUrl; use std::borrow::Cow; +use std::fmt; use std::fs::File; -use std::io::{BufRead, BufReader, Seek, SeekFrom}; +use std::io::{BufReader, BufRead}; use std::mem; -use std::ops::Bound; use std::str; -use std::sync::atomic::Ordering; use std::sync::{Arc, Mutex}; +use std::sync::atomic::Ordering; use std::thread; - -lazy_static! { - static ref X_CONTENT_TYPE_OPTIONS: HeaderName = - HeaderName::from_static("x-content-type-options"); -} +use subresource_integrity::is_response_integrity_valid; const FILE_CHUNK_SIZE: usize = 32768; //32 KB -pub type Target<'a> = &'a mut (dyn FetchTaskTarget + Send); +pub type Target<'a> = &'a mut (FetchTaskTarget + Send); pub enum Data { Payload(Vec), @@ -88,16 +83,16 @@ impl CancellationListener { pub type DoneChannel = Option<(Sender, Receiver)>; /// [Fetch](https://fetch.spec.whatwg.org#concept-fetch) -pub fn fetch(request: &mut Request, target: Target, context: &FetchContext) { +pub fn fetch(request: &mut Request, + target: Target, + context: &FetchContext) { fetch_with_cors_cache(request, &mut CorsCache::new(), target, context); } -pub fn fetch_with_cors_cache( - request: &mut Request, - cache: &mut CorsCache, - target: Target, - context: &FetchContext, -) { +pub fn fetch_with_cors_cache(request: &mut Request, + cache: &mut CorsCache, + target: Target, + context: &FetchContext) { // Step 1. if request.window == Window::Client { // TODO: Set window to request's client object if client is a Window object @@ -133,27 +128,21 @@ pub fn fetch_with_cors_cache( } /// [Main fetch](https://fetch.spec.whatwg.org/#concept-main-fetch) -pub fn main_fetch( - request: &mut Request, - cache: &mut CorsCache, - cors_flag: bool, - recursive_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +pub fn main_fetch(request: &mut Request, + cache: &mut CorsCache, + cors_flag: bool, + recursive_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { // Step 1. let mut response = None; // Step 2. if request.local_urls_only { - if !matches!( - request.current_url().scheme(), - "about" | "blob" | "data" | "filesystem" - ) { - response = Some(Response::network_error(NetworkError::Internal( - "Non-local scheme".into(), - ))); + if !matches!(request.current_url().scheme(), "about" | "blob" | "data" | "filesystem") { + response = Some(Response::network_error(NetworkError::Internal("Non-local scheme".into()))); } } @@ -165,9 +154,7 @@ pub fn main_fetch( // Step 5. if should_be_blocked_due_to_bad_port(&request.current_url()) { - response = Some(Response::network_error(NetworkError::Internal( - "Request attempted on bad port".into(), - ))); + response = Some(Response::network_error(NetworkError::Internal("Request attempted on bad port".into()))); } // TODO: handle blocking as mixed content. // TODO: handle blocking by content security policy. @@ -176,9 +163,7 @@ pub fn main_fetch( // TODO: handle request's client's referrer policy. // Step 7. - request.referrer_policy = request - .referrer_policy - .or(Some(ReferrerPolicy::NoReferrerWhenDowngrade)); + request.referrer_policy = request.referrer_policy.or(Some(ReferrerPolicy::NoReferrerWhenDowngrade)); // Step 8. { @@ -187,19 +172,17 @@ pub fn main_fetch( Referrer::Client => { // FIXME(#14507): We should never get this value here; it should // already have been handled in the script thread. - request.headers.remove(header::REFERER); + request.headers.remove::(); None }, Referrer::ReferrerUrl(url) => { - request.headers.remove(header::REFERER); + request.headers.remove::(); let current_url = request.current_url().clone(); - determine_request_referrer( - &mut request.headers, - request.referrer_policy.unwrap(), - url, - current_url, - ) - }, + determine_request_referrer(&mut request.headers, + request.referrer_policy.unwrap(), + url, + current_url) + } }; if let Some(referrer_url) = referrer_url { request.referrer = Referrer::ReferrerUrl(referrer_url); @@ -210,12 +193,8 @@ pub fn main_fetch( // TODO: handle FTP URLs. // Step 10. - context - .state - .hsts_list - .read() - .unwrap() - .switch_known_hsts_host_domain_url_to_https(request.current_url_mut()); + context.state.hsts_list.read().unwrap().switch_known_hsts_host_domain_url_to_https( + request.current_url_mut()); // Step 11. // Not applicable: see fetch_async. @@ -235,49 +214,47 @@ pub fn main_fetch( // and about: schemes, but CSS tests will break on loading Ahem // since we load them through a file: URL. current_url.scheme() == "about" || - request.mode == RequestMode::Navigate - { + request.mode == RequestMode::Navigate { // Substep 1. request.response_tainting = ResponseTainting::Basic; // Substep 2. scheme_fetch(request, cache, target, done_chan, context) + } else if request.mode == RequestMode::SameOrigin { Response::network_error(NetworkError::Internal("Cross-origin response".into())) + } else if request.mode == RequestMode::NoCors { // Substep 1. request.response_tainting = ResponseTainting::Opaque; // Substep 2. scheme_fetch(request, cache, target, done_chan, context) + } else if !matches!(current_url.scheme(), "http" | "https") { Response::network_error(NetworkError::Internal("Non-http scheme".into())) + } else if request.use_cors_preflight || (request.unsafe_request && - (!is_cors_safelisted_method(&request.method) || request - .headers - .iter() - .any(|(name, value)| !is_cors_safelisted_request_header(&name, &value)))) - { + (!is_cors_safelisted_method(&request.method) || + request.headers.iter().any(|h| !is_cors_safelisted_request_header(&h)))) { // Substep 1. request.response_tainting = ResponseTainting::CorsTainting; // Substep 2. - let response = http_fetch( - request, cache, true, true, false, target, done_chan, context, - ); + let response = http_fetch(request, cache, true, true, false, + target, done_chan, context); // Substep 3. if response.is_network_error() { // TODO clear cache entries using request } // Substep 4. response + } else { // Substep 1. request.response_tainting = ResponseTainting::CorsTainting; // Substep 2. - http_fetch( - request, cache, true, false, false, target, done_chan, context, - ) + http_fetch(request, cache, true, false, false, target, done_chan, context) } }); @@ -291,25 +268,18 @@ pub fn main_fetch( // Substep 1. if request.response_tainting == ResponseTainting::CorsTainting { // Subsubstep 1. - let header_names: Option> = response - .headers - .typed_get::() - .map(|v| v.iter().collect()); + let header_names = response.headers.get::(); match header_names { // Subsubstep 2. - Some(ref list) if request.credentials_mode != CredentialsMode::Include => { + Some(list) if request.credentials_mode != CredentialsMode::Include => { if list.len() == 1 && list[0] == "*" { - response.cors_exposed_header_name_list = response - .headers - .iter() - .map(|(name, _)| name.as_str().to_owned()) - .collect(); + response.cors_exposed_header_name_list = + response.headers.iter().map(|h| h.name().to_owned()).collect(); } }, // Subsubstep 3. Some(list) => { - response.cors_exposed_header_name_list = - list.iter().map(|h| h.as_str().to_owned()).collect(); + response.cors_exposed_header_name_list = list.iter().map(|h| (**h).clone()).collect(); }, _ => (), } @@ -329,16 +299,13 @@ pub fn main_fetch( let internal_error = { // Tests for steps 17 and 18, before step 15 for borrowing concerns. let response_is_network_error = response.is_network_error(); - let should_replace_with_nosniff_error = !response_is_network_error && - should_be_blocked_due_to_nosniff(request.destination, &response.headers); - let should_replace_with_mime_type_error = !response_is_network_error && - should_be_blocked_due_to_mime_type(request.destination, &response.headers); + let should_replace_with_nosniff_error = + !response_is_network_error && should_be_blocked_due_to_nosniff(request.destination, &response.headers); + let should_replace_with_mime_type_error = + !response_is_network_error && should_be_blocked_due_to_mime_type(request.destination, &response.headers); // Step 15. - let mut network_error_response = response - .get_network_error() - .cloned() - .map(Response::network_error); + let mut network_error_response = response.get_network_error().cloned().map(Response::network_error); let internal_response = if let Some(error_response) = network_error_response.as_mut() { error_response } else { @@ -354,29 +321,27 @@ pub fn main_fetch( // TODO: handle blocking as mixed content. // TODO: handle blocking by content security policy. let blocked_error_response; - let internal_response = if should_replace_with_nosniff_error { - // Defer rebinding result - blocked_error_response = - Response::network_error(NetworkError::Internal("Blocked by nosniff".into())); - &blocked_error_response - } else if should_replace_with_mime_type_error { - // Defer rebinding result - blocked_error_response = - Response::network_error(NetworkError::Internal("Blocked by mime type".into())); - &blocked_error_response - } else { - internal_response - }; + let internal_response = + if should_replace_with_nosniff_error { + // Defer rebinding result + blocked_error_response = Response::network_error(NetworkError::Internal("Blocked by nosniff".into())); + &blocked_error_response + } else if should_replace_with_mime_type_error { + // Defer rebinding result + blocked_error_response = Response::network_error(NetworkError::Internal("Blocked by mime type".into())); + &blocked_error_response + } else { + internal_response + }; // Step 18. // We check `internal_response` since we did not mutate `response` // in the previous step. let not_network_error = !response_is_network_error && !internal_response.is_network_error(); - if not_network_error && - (is_null_body_status(&internal_response.status) || match request.method { - Method::HEAD | Method::CONNECT => true, - _ => false, - }) { + if not_network_error && (is_null_body_status(&internal_response.status) || + match request.method { + Method::Head | Method::Connect => true, + _ => false }) { // when Fetch is used only asynchronously, we will need to make sure // that nothing tries to write to the body at this point let mut body = internal_response.body.lock().unwrap(); @@ -403,11 +368,8 @@ pub fn main_fetch( // Step 19.2. let ref integrity_metadata = &request.integrity_metadata; if response.termination_reason.is_none() && - !is_response_integrity_valid(integrity_metadata, &response) - { - Response::network_error(NetworkError::Internal( - "Subresource integrity validation failed".into(), - )) + !is_response_integrity_valid(integrity_metadata, &response) { + Response::network_error(NetworkError::Internal("Subresource integrity validation failed".into())) } else { response } @@ -443,7 +405,7 @@ pub fn main_fetch( // Step 23. if !response_loaded { - wait_for_response(&mut response, target, done_chan); + wait_for_response(&mut response, target, done_chan); } // Step 24. @@ -463,11 +425,8 @@ pub fn main_fetch( fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut DoneChannel) { if let Some(ref ch) = *done_chan { loop { - match ch - .1 - .recv() - .expect("fetch worker should always send Done before terminating") - { + match ch.1.recv() + .expect("fetch worker should always send Done before terminating") { Data::Payload(vec) => { target.process_response_chunk(vec); }, @@ -475,7 +434,7 @@ fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut Do Data::Cancelled => { response.aborted.store(true, Ordering::Relaxed); break; - }, + } } } } else { @@ -492,166 +451,106 @@ fn wait_for_response(response: &mut Response, target: Target, done_chan: &mut Do } /// [Scheme fetch](https://fetch.spec.whatwg.org#scheme-fetch) -fn scheme_fetch( - request: &mut Request, - cache: &mut CorsCache, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +fn scheme_fetch(request: &mut Request, + cache: &mut CorsCache, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { let url = request.current_url(); match url.scheme() { "about" if url.path() == "blank" => { let mut response = Response::new(url); - response - .headers - .typed_insert(ContentType::from(mime::TEXT_HTML_UTF_8)); + response.headers.set(ContentType(mime!(Text / Html; Charset = Utf8))); *response.body.lock().unwrap() = ResponseBody::Done(vec![]); response }, - "http" | "https" => http_fetch( - request, cache, false, false, false, target, done_chan, context, - ), - - "data" => match decode(&url) { - Ok((mime, bytes)) => { - let mut response = Response::new(url); - *response.body.lock().unwrap() = ResponseBody::Done(bytes); - response.headers.typed_insert(ContentType::from(mime)); - response - }, - Err(_) => { - Response::network_error(NetworkError::Internal("Decoding data URL failed".into())) - }, + "http" | "https" => { + http_fetch(request, cache, false, false, false, target, done_chan, context) }, - "file" => { - if request.method != Method::GET { - return Response::network_error(NetworkError::Internal( - "Unexpected method for file".into(), - )); + "data" => { + match decode(&url) { + Ok((mime, bytes)) => { + let mut response = Response::new(url); + *response.body.lock().unwrap() = ResponseBody::Done(bytes); + response.headers.set(ContentType(mime)); + response + }, + Err(_) => Response::network_error(NetworkError::Internal("Decoding data URL failed".into())) } - if let Ok(file_path) = url.to_file_path() { - if let Ok(file) = File::open(file_path.clone()) { - let mime = guess_mime_type(file_path); + }, - let mut response = Response::new(url); - response.headers.typed_insert(ContentType::from(mime)); - - let (done_sender, done_receiver) = channel(); - *done_chan = Some((done_sender.clone(), done_receiver)); - *response.body.lock().unwrap() = ResponseBody::Receiving(vec![]); - - let res_body = response.body.clone(); - - let cancellation_listener = context.cancellation_listener.clone(); - - let (start, end) = if let Some(ref range) = request.headers.typed_get::() - { - match range - .iter() - .collect::, Bound)>>() - .first() - { - Some(&(Bound::Included(start), Bound::Unbounded)) => (start, None), - Some(&(Bound::Included(start), Bound::Included(end))) => { - // `end` should be less or equal to `start`. - (start, Some(u64::max(start, end))) - }, - Some(&(Bound::Unbounded, Bound::Included(offset))) => { - if let Ok(metadata) = file.metadata() { - // `offset` cannot be bigger than the file size. - (metadata.len() - u64::min(metadata.len(), offset), None) - } else { - (0, None) - } + "file" => { + if request.method == Method::Get { + match url.to_file_path() { + Ok(file_path) => { + match File::open(file_path.clone()) { + Ok(mut file) => { + let mime = guess_mime_type(file_path); + + let mut response = Response::new(url); + response.headers.set(ContentType(mime)); + + let (done_sender, done_receiver) = channel(); + *done_chan = Some((done_sender.clone(), done_receiver)); + *response.body.lock().unwrap() = ResponseBody::Receiving(vec![]); + + let mut res_body = response.body.clone(); + + let cancellation_listener = context.cancellation_listener.clone(); + + thread::Builder::new().name("fetch file worker thread".to_string()).spawn(move || { + let mut reader = BufReader::with_capacity(FILE_CHUNK_SIZE, file); + loop { + if cancellation_listener.lock().unwrap().cancelled() { + *res_body.lock().unwrap() = ResponseBody::Done(vec![]); + let _ = done_sender.send(Data::Cancelled); + return; + } + let length = { + let mut buffer = reader.fill_buf().unwrap().to_vec(); + let buffer_len = buffer.len(); + if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { + body.extend_from_slice(&buffer); + let _ = done_sender.send(Data::Payload(buffer)); + } + buffer_len + }; + if length == 0 { + let mut body = res_body.lock().unwrap(); + let completed_body = match *body { + ResponseBody::Receiving(ref mut body) => { + mem::replace(body, vec![]) + }, + _ => vec![], + }; + *body = ResponseBody::Done(completed_body); + let _ = done_sender.send(Data::Done); + break; + } + reader.consume(length); + } + }).expect("Failed to create fetch file worker thread"); + response }, - _ => (0, None), + _ => Response::network_error(NetworkError::Internal("Opening file failed".into())), } - } else { - (0, None) - }; - - thread::Builder::new() - .name("fetch file worker thread".to_string()) - .spawn(move || { - let mut reader = BufReader::with_capacity(FILE_CHUNK_SIZE, file); - if reader.seek(SeekFrom::Start(start)).is_err() { - warn!("Fetch - could not seek to {:?}", start); - } - - loop { - if cancellation_listener.lock().unwrap().cancelled() { - *res_body.lock().unwrap() = ResponseBody::Done(vec![]); - let _ = done_sender.send(Data::Cancelled); - return; - } - let length = { - let buffer = reader.fill_buf().unwrap().to_vec(); - let mut buffer_len = buffer.len(); - if let ResponseBody::Receiving(ref mut body) = - *res_body.lock().unwrap() - { - let offset = usize::min( - { - if let Some(end) = end { - let remaining_bytes = - end as usize - start as usize - body.len(); - if remaining_bytes <= FILE_CHUNK_SIZE { - // This is the last chunk so we set buffer - // len to 0 to break the reading loop. - buffer_len = 0; - remaining_bytes - } else { - FILE_CHUNK_SIZE - } - } else { - FILE_CHUNK_SIZE - } - }, - buffer.len(), - ); - body.extend_from_slice(&buffer[0..offset]); - let _ = done_sender.send(Data::Payload(buffer)); - } - buffer_len - }; - if length == 0 { - let mut body = res_body.lock().unwrap(); - let completed_body = match *body { - ResponseBody::Receiving(ref mut body) => { - mem::replace(body, vec![]) - }, - _ => vec![], - }; - *body = ResponseBody::Done(completed_body); - let _ = done_sender.send(Data::Done); - break; - } - reader.consume(length); - } - }) - .expect("Failed to create fetch file worker thread"); - response - } else { - Response::network_error(NetworkError::Internal("Opening file failed".into())) + }, + _ => Response::network_error(NetworkError::Internal("Constructing file path failed".into())) } } else { - Response::network_error(NetworkError::Internal( - "Constructing file path failed".into(), - )) + Response::network_error(NetworkError::Internal("Unexpected method for file".into())) } }, "blob" => { println!("Loading blob {}", url.as_str()); // Step 2. - if request.method != Method::GET { - return Response::network_error(NetworkError::Internal( - "Unexpected method for blob".into(), - )); + if request.method != Method::Get { + return Response::network_error(NetworkError::Internal("Unexpected method for blob".into())); } match load_blob_sync(url.clone(), context.filemanager.clone()) { @@ -673,127 +572,145 @@ fn scheme_fetch( Response::network_error(NetworkError::Internal("Unexpected scheme".into())) }, - _ => Response::network_error(NetworkError::Internal("Unexpected scheme".into())), + _ => Response::network_error(NetworkError::Internal("Unexpected scheme".into())) } } /// -pub fn is_cors_safelisted_request_header(name: &HeaderName, value: &HeaderValue) -> bool { - if name == header::CONTENT_TYPE { - if let Some(m) = value.to_str().ok().and_then(|s| s.parse::().ok()) { - m.type_() == mime::TEXT && m.subtype() == mime::PLAIN || - m.type_() == mime::APPLICATION && m.subtype() == mime::WWW_FORM_URLENCODED || - m.type_() == mime::MULTIPART && m.subtype() == mime::FORM_DATA - } else { - false +pub fn is_cors_safelisted_request_header(h: &HeaderView) -> bool { + if h.is::() { + match h.value() { + Some(&ContentType(Mime(TopLevel::Text, SubLevel::Plain, _))) | + Some(&ContentType(Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _))) | + Some(&ContentType(Mime(TopLevel::Multipart, SubLevel::FormData, _))) => true, + _ => false + } } else { - name == header::ACCEPT || - name == header::ACCEPT_LANGUAGE || - name == header::CONTENT_LANGUAGE + h.is::() || h.is::() || h.is::() } } /// pub fn is_cors_safelisted_method(m: &Method) -> bool { match *m { - Method::GET | Method::HEAD | Method::POST => true, - _ => false, + Method::Get | Method::Head | Method::Post => true, + _ => false } } -fn is_null_body_status(status: &Option<(StatusCode, String)>) -> bool { +fn is_null_body_status(status: &Option) -> bool { match *status { - Some((status, _)) => match status { - StatusCode::SWITCHING_PROTOCOLS | - StatusCode::NO_CONTENT | - StatusCode::RESET_CONTENT | - StatusCode::NOT_MODIFIED => true, - _ => false, + Some(status) => match status { + StatusCode::SwitchingProtocols | StatusCode::NoContent | + StatusCode::ResetContent | StatusCode::NotModified => true, + _ => false }, - _ => false, + _ => false } } /// -pub fn should_be_blocked_due_to_nosniff( - destination: Destination, - response_headers: &HeaderMap, -) -> bool { +pub fn should_be_blocked_due_to_nosniff(destination: Destination, response_headers: &Headers) -> bool { + /// + /// This is needed to parse `X-Content-Type-Options` according to spec, + /// which requires that we inspect only the first value. + /// + /// A [unit-like struct](https://doc.rust-lang.org/book/structs.html#unit-like-structs) + /// is sufficient since a valid header implies that we use `nosniff`. + #[derive(Clone, Copy, Debug)] + struct XContentTypeOptions; + + impl Header for XContentTypeOptions { + fn header_name() -> &'static str { + "X-Content-Type-Options" + } + + /// https://fetch.spec.whatwg.org/#should-response-to-request-be-blocked-due-to-nosniff%3F #2 + fn parse_header(raw: &[Vec]) -> HyperResult { + raw.first() + .and_then(|v| str::from_utf8(v).ok()) + .and_then(|s| if s.trim().eq_ignore_ascii_case("nosniff") { + Some(XContentTypeOptions) + } else { + None + }) + .ok_or(Error::Header) + } + } + + impl HeaderFormat for XContentTypeOptions { + fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("nosniff") + } + } + // Steps 1-3. - // TODO(eijebong): Replace this once typed headers allow custom ones... - if response_headers - .get("x-content-type-options") - .map_or(true, |val| { - val.to_str().unwrap_or("").to_lowercase() != "nosniff" - }) { + if response_headers.get::().is_none() { return false; } // Step 4 // Note: an invalid MIME type will produce a `None`. - let content_type_header = response_headers.typed_get::(); + let content_type_header = response_headers.get::(); /// #[inline] fn is_javascript_mime_type(mime_type: &Mime) -> bool { let javascript_mime_types: [Mime; 16] = [ - "application/ecmascript".parse().unwrap(), - "application/javascript".parse().unwrap(), - "application/x-ecmascript".parse().unwrap(), - "application/x-javascript".parse().unwrap(), - "text/ecmascript".parse().unwrap(), - "text/javascript".parse().unwrap(), - "text/javascript1.0".parse().unwrap(), - "text/javascript1.1".parse().unwrap(), - "text/javascript1.2".parse().unwrap(), - "text/javascript1.3".parse().unwrap(), - "text/javascript1.4".parse().unwrap(), - "text/javascript1.5".parse().unwrap(), - "text/jscript".parse().unwrap(), - "text/livescript".parse().unwrap(), - "text/x-ecmascript".parse().unwrap(), - "text/x-javascript".parse().unwrap(), + mime!(Application / ("ecmascript")), + mime!(Application / ("javascript")), + mime!(Application / ("x-ecmascript")), + mime!(Application / ("x-javascript")), + mime!(Text / ("ecmascript")), + mime!(Text / ("javascript")), + mime!(Text / ("javascript1.0")), + mime!(Text / ("javascript1.1")), + mime!(Text / ("javascript1.2")), + mime!(Text / ("javascript1.3")), + mime!(Text / ("javascript1.4")), + mime!(Text / ("javascript1.5")), + mime!(Text / ("jscript")), + mime!(Text / ("livescript")), + mime!(Text / ("x-ecmascript")), + mime!(Text / ("x-javascript")), ]; - javascript_mime_types - .iter() - .any(|mime| mime.type_() == mime_type.type_() && mime.subtype() == mime_type.subtype()) + javascript_mime_types.iter() + .any(|mime| mime.0 == mime_type.0 && mime.1 == mime_type.1) } + // Assumes str::starts_with is equivalent to mime::TopLevel match content_type_header { // Step 6 - Some(ref ct) if destination.is_script_like() => { - !is_javascript_mime_type(&ct.clone().into()) - }, + Some(&ContentType(ref mime_type)) if destination.is_script_like() + => !is_javascript_mime_type(mime_type), // Step 7 - Some(ref ct) if destination == Destination::Style => { - let m: mime::Mime = ct.clone().into(); - m.type_() != mime::TEXT && m.subtype() != mime::CSS - }, + Some(&ContentType(Mime(ref tl, ref sl, _))) if destination == Destination::Style + => *tl != TopLevel::Text && *sl != SubLevel::Css, None if destination == Destination::Style || destination.is_script_like() => true, // Step 8 - _ => false, + _ => false } } /// -fn should_be_blocked_due_to_mime_type( - destination: Destination, - response_headers: &HeaderMap, -) -> bool { +fn should_be_blocked_due_to_mime_type(destination: Destination, response_headers: &Headers) -> bool { // Step 1 - let mime_type: mime::Mime = match response_headers.typed_get::() { - Some(header) => header.into(), + let mime_type = match response_headers.get::() { + Some(header) => header, None => return false, }; // Step 2-3 - destination.is_script_like() && match mime_type.type_() { - mime::AUDIO | mime::VIDEO | mime::IMAGE => true, - mime::TEXT if mime_type.subtype() == mime::CSV => true, + destination.is_script_like() && match *mime_type { + ContentType(Mime(TopLevel::Audio, _, _)) | + ContentType(Mime(TopLevel::Video, _, _)) | + ContentType(Mime(TopLevel::Image, _, _)) => true, + ContentType(Mime(TopLevel::Text, SubLevel::Ext(ref ext), _)) => ext == "csv", + // Step 4 _ => false, } @@ -810,17 +727,14 @@ pub fn should_be_blocked_due_to_bad_port(url: &ServoUrl) -> bool { // If there is no explicit port, this means the default one is used for // the given scheme, and thus this means the request should not be blocked // due to a bad port. - let port = if let Some(port) = url.port() { - port - } else { - return false; - }; + let port = if let Some(port) = url.port() { port } else { return false }; // Step 4. if scheme == "ftp" && (port == 20 || port == 21) { return false; } + // Step 5. if is_network_scheme(scheme) && is_bad_port(port) { return true; @@ -838,10 +752,12 @@ fn is_network_scheme(scheme: &str) -> bool { /// fn is_bad_port(port: u16) -> bool { static BAD_PORTS: [u16; 64] = [ - 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 77, 79, 87, 95, 101, 102, - 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, 513, - 514, 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, 636, 993, 995, 2049, 3659, 4045, - 6000, 6665, 6666, 6667, 6668, 6669, + 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, + 43, 53, 77, 79, 87, 95, 101, 102, 103, 104, 109, 110, 111, + 113, 115, 117, 119, 123, 135, 139, 143, 179, 389, 465, 512, + 513, 514, 515, 526, 530, 531, 532, 540, 556, 563, 587, 601, + 636, 993, 995, 2049, 3659, 4045, 6000, 6665, 6666, 6667, + 6668, 6669 ]; BAD_PORTS.binary_search(&port).is_ok() diff --git a/components/net/filemanager_thread.rs b/components/net/filemanager_thread.rs index 966f8a21bcb8..3dda46a979d5 100644 --- a/components/net/filemanager_thread.rs +++ b/components/net/filemanager_thread.rs @@ -7,17 +7,15 @@ use ipc_channel::ipc::{self, IpcSender}; use mime_guess::guess_mime_type_opt; use net_traits::blob_url_store::{BlobBuf, BlobURLStoreError}; use net_traits::filemanager_thread::{FileManagerResult, FileManagerThreadMsg, FileOrigin}; -use net_traits::filemanager_thread::{ - FileManagerThreadError, ReadFileProgress, RelativePos, SelectedFile, -}; +use net_traits::filemanager_thread::{FileManagerThreadError, ReadFileProgress, RelativePos, SelectedFile}; use servo_config::prefs::PREFS; use std::collections::HashMap; use std::fs::File; use std::io::{Read, Seek, SeekFrom}; use std::ops::Index; use std::path::{Path, PathBuf}; -use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, RwLock}; +use std::sync::atomic::{self, AtomicBool, AtomicUsize, Ordering}; use std::thread; use url::Url; use uuid::Uuid; @@ -36,7 +34,7 @@ struct FileStoreEntry { /// UUIDs only become valid blob URIs when explicitly requested /// by the user with createObjectURL. Validity can be revoked as well. /// (The UUID is the one that maps to this entry in `FileManagerStore`) - is_valid_url: AtomicBool, + is_valid_url: AtomicBool } #[derive(Clone)] @@ -73,38 +71,29 @@ impl FileManager { } } - pub fn read_file( - &self, - sender: IpcSender>, - id: Uuid, - check_url_validity: bool, - origin: FileOrigin, - ) { + pub fn read_file(&self, + sender: IpcSender>, + id: Uuid, + check_url_validity: bool, + origin: FileOrigin) { let store = self.store.clone(); - thread::Builder::new() - .name("read file".to_owned()) - .spawn(move || { - if let Err(e) = store.try_read_file(&sender, id, check_url_validity, origin) { - let _ = sender.send(Err(FileManagerThreadError::BlobURLStoreError(e))); - } - }) - .expect("Thread spawning failed"); + thread::Builder::new().name("read file".to_owned()).spawn(move || { + if let Err(e) = store.try_read_file(&sender, id, check_url_validity, + origin) { + let _ = sender.send(Err(FileManagerThreadError::BlobURLStoreError(e))); + } + }).expect("Thread spawning failed"); } - pub fn promote_memory( - &self, - blob_buf: BlobBuf, - set_valid: bool, - sender: IpcSender>, - origin: FileOrigin, - ) { + pub fn promote_memory(&self, + blob_buf: BlobBuf, + set_valid: bool, + sender: IpcSender>, + origin: FileOrigin) { let store = self.store.clone(); - thread::Builder::new() - .name("transfer memory".to_owned()) - .spawn(move || { - store.promote_memory(blob_buf, set_valid, sender, origin); - }) - .expect("Thread spawning failed"); + thread::Builder::new().name("transfer memory".to_owned()).spawn(move || { + store.promote_memory(blob_buf, set_valid, sender, origin); + }).expect("Thread spawning failed"); } /// Message handler @@ -113,41 +102,35 @@ impl FileManager { FileManagerThreadMsg::SelectFile(filter, sender, origin, opt_test_path) => { let store = self.store.clone(); let embedder = self.embedder_proxy.clone(); - thread::Builder::new() - .name("select file".to_owned()) - .spawn(move || { - store.select_file(filter, sender, origin, opt_test_path, embedder); - }) - .expect("Thread spawning failed"); - }, + thread::Builder::new().name("select file".to_owned()).spawn(move || { + store.select_file(filter, sender, origin, opt_test_path, embedder); + }).expect("Thread spawning failed"); + } FileManagerThreadMsg::SelectFiles(filter, sender, origin, opt_test_paths) => { let store = self.store.clone(); let embedder = self.embedder_proxy.clone(); - thread::Builder::new() - .name("select files".to_owned()) - .spawn(move || { - store.select_files(filter, sender, origin, opt_test_paths, embedder); - }) - .expect("Thread spawning failed"); - }, + thread::Builder::new().name("select files".to_owned()).spawn(move || { + store.select_files(filter, sender, origin, opt_test_paths, embedder); + }).expect("Thread spawning failed"); + } FileManagerThreadMsg::ReadFile(sender, id, check_url_validity, origin) => { self.read_file(sender, id, check_url_validity, origin); - }, + } FileManagerThreadMsg::PromoteMemory(blob_buf, set_valid, sender, origin) => { self.promote_memory(blob_buf, set_valid, sender, origin); - }, - FileManagerThreadMsg::AddSlicedURLEntry(id, rel_pos, sender, origin) => { + } + FileManagerThreadMsg::AddSlicedURLEntry(id, rel_pos, sender, origin) =>{ self.store.add_sliced_url_entry(id, rel_pos, sender, origin); - }, + } FileManagerThreadMsg::DecRef(id, origin, sender) => { let _ = sender.send(self.store.dec_ref(&id, &origin)); - }, + } FileManagerThreadMsg::RevokeBlobURL(id, origin, sender) => { let _ = sender.send(self.store.set_blob_url_validity(false, &id, &origin)); - }, + } FileManagerThreadMsg::ActivateBlobURL(id, sender, origin) => { let _ = sender.send(self.store.set_blob_url_validity(true, &id, &origin)); - }, + } } } } @@ -167,12 +150,8 @@ impl FileManagerStore { } /// Copy out the file backend implementation content - fn get_impl( - &self, - id: &Uuid, - origin_in: &FileOrigin, - check_url_validity: bool, - ) -> Result { + fn get_impl(&self, id: &Uuid, origin_in: &FileOrigin, + check_url_validity: bool) -> Result { match self.entries.read().unwrap().get(id) { Some(ref entry) => { if *origin_in != *entry.origin { @@ -185,7 +164,7 @@ impl FileManagerStore { Ok(entry.file_impl.clone()) } } - }, + } None => Err(BlobURLStoreError::InvalidFileID), } } @@ -198,7 +177,7 @@ impl FileManagerStore { self.entries.write().unwrap().remove(id); } - fn inc_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { + fn inc_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError>{ match self.entries.read().unwrap().get(id) { Some(entry) => { if entry.origin == *origin_in { @@ -207,53 +186,41 @@ impl FileManagerStore { } else { Err(BlobURLStoreError::InvalidOrigin) } - }, + } None => Err(BlobURLStoreError::InvalidFileID), } } - fn add_sliced_url_entry( - &self, - parent_id: Uuid, - rel_pos: RelativePos, - sender: IpcSender>, - origin_in: FileOrigin, - ) { + fn add_sliced_url_entry(&self, parent_id: Uuid, rel_pos: RelativePos, + sender: IpcSender>, + origin_in: FileOrigin) { match self.inc_ref(&parent_id, &origin_in) { Ok(_) => { let new_id = Uuid::new_v4(); - self.insert( - new_id, - FileStoreEntry { - origin: origin_in, - file_impl: FileImpl::Sliced(parent_id, rel_pos), - refs: AtomicUsize::new(1), - // Valid here since AddSlicedURLEntry implies URL creation - // from a BlobImpl::Sliced - is_valid_url: AtomicBool::new(true), - }, - ); + self.insert(new_id, FileStoreEntry { + origin: origin_in, + file_impl: FileImpl::Sliced(parent_id, rel_pos), + refs: AtomicUsize::new(1), + // Valid here since AddSlicedURLEntry implies URL creation + // from a BlobImpl::Sliced + is_valid_url: AtomicBool::new(true), + }); // We assume that the returned id will be held by BlobImpl::File let _ = sender.send(Ok(new_id)); - }, + } Err(e) => { let _ = sender.send(Err(e)); - }, + } } } - fn query_files_from_embedder( - &self, - patterns: Vec, - multiple_files: bool, - embedder_proxy: EmbedderProxy, - ) -> Option> { + fn query_files_from_embedder(&self, + patterns: Vec, + multiple_files: bool, + embedder_proxy: EmbedderProxy) -> Option> { let (ipc_sender, ipc_receiver) = ipc::channel().expect("Failed to create IPC channel!"); - let msg = ( - None, - EmbedderMsg::SelectFiles(patterns, multiple_files, ipc_sender), - ); + let msg = (None, EmbedderMsg::SelectFiles(patterns, multiple_files, ipc_sender)); embedder_proxy.send(msg); match ipc_receiver.recv() { @@ -261,26 +228,23 @@ impl FileManagerStore { Err(e) => { warn!("Failed to receive files from embedder ({}).", e); None - }, + } } } - fn select_file( - &self, - patterns: Vec, - sender: IpcSender>, - origin: FileOrigin, - opt_test_path: Option, - embedder_proxy: EmbedderProxy, - ) { + fn select_file(&self, + patterns: Vec, + sender: IpcSender>, + origin: FileOrigin, + opt_test_path: Option, + embedder_proxy: EmbedderProxy) { // Check if the select_files preference is enabled // to ensure process-level security against compromised script; // Then try applying opt_test_path directly for testing convenience let opt_s = if select_files_pref_enabled() { opt_test_path } else { - self.query_files_from_embedder(patterns, false, embedder_proxy) - .and_then(|mut x| x.pop()) + self.query_files_from_embedder(patterns, false, embedder_proxy).and_then(|mut x| x.pop()) }; match opt_s { @@ -288,22 +252,20 @@ impl FileManagerStore { let selected_path = Path::new(&s); let result = self.create_entry(selected_path, &origin); let _ = sender.send(result); - }, + } None => { let _ = sender.send(Err(FileManagerThreadError::UserCancelled)); return; - }, + } } } - fn select_files( - &self, - patterns: Vec, - sender: IpcSender>>, - origin: FileOrigin, - opt_test_paths: Option>, - embedder_proxy: EmbedderProxy, - ) { + fn select_files(&self, + patterns: Vec, + sender: IpcSender>>, + origin: FileOrigin, + opt_test_paths: Option>, + embedder_proxy: EmbedderProxy) { // Check if the select_files preference is enabled // to ensure process-level security against compromised script; // Then try applying opt_test_paths directly for testing convenience @@ -329,42 +291,30 @@ impl FileManagerStore { Err(e) => { let _ = sender.send(Err(e)); return; - }, + } }; } let _ = sender.send(Ok(replies)); - }, + } None => { let _ = sender.send(Err(FileManagerThreadError::UserCancelled)); return; - }, + } } } - fn create_entry( - &self, - file_path: &Path, - origin: &str, - ) -> Result { + fn create_entry(&self, file_path: &Path, origin: &str) -> Result { use net_traits::filemanager_thread::FileManagerThreadError::FileSystemError; let file = File::open(file_path).map_err(|e| FileSystemError(e.to_string()))?; - let metadata = file - .metadata() - .map_err(|e| FileSystemError(e.to_string()))?; - let modified = metadata - .modified() - .map_err(|e| FileSystemError(e.to_string()))?; - let elapsed = modified - .elapsed() - .map_err(|e| FileSystemError(e.to_string()))?; + let metadata = file.metadata().map_err(|e| FileSystemError(e.to_string()))?; + let modified = metadata.modified().map_err(|e| FileSystemError(e.to_string()))?; + let elapsed = modified.elapsed().map_err(|e| FileSystemError(e.to_string()))?; // Unix Epoch: https://doc.servo.org/std/time/constant.UNIX_EPOCH.html let modified_epoch = elapsed.as_secs() * 1000 + elapsed.subsec_nanos() as u64 / 1000000; let file_size = metadata.len(); - let file_name = file_path - .file_name() - .ok_or(FileSystemError("Invalid filepath".to_string()))?; + let file_name = file_path.file_name().ok_or(FileSystemError("Invalid filepath".to_string()))?; let file_impl = FileImpl::MetaDataOnly(FileMetaData { path: file_path.to_path_buf(), @@ -374,21 +324,18 @@ impl FileManagerStore { let id = Uuid::new_v4(); - self.insert( - id, - FileStoreEntry { - origin: origin.to_string(), - file_impl: file_impl, - refs: AtomicUsize::new(1), - // Invalid here since create_entry is called by file selection - is_valid_url: AtomicBool::new(false), - }, - ); + self.insert(id, FileStoreEntry { + origin: origin.to_string(), + file_impl: file_impl, + refs: AtomicUsize::new(1), + // Invalid here since create_entry is called by file selection + is_valid_url: AtomicBool::new(false), + }); let filename_path = Path::new(file_name); let type_string = match guess_mime_type_opt(filename_path) { Some(x) => format!("{}", x), - None => "".to_string(), + None => "".to_string(), }; Ok(SelectedFile { @@ -400,14 +347,9 @@ impl FileManagerStore { }) } - fn get_blob_buf( - &self, - sender: &IpcSender>, - id: &Uuid, - origin_in: &FileOrigin, - rel_pos: RelativePos, - check_url_validity: bool, - ) -> Result<(), BlobURLStoreError> { + fn get_blob_buf(&self, sender: &IpcSender>, + id: &Uuid, origin_in: &FileOrigin, rel_pos: RelativePos, + check_url_validity: bool) -> Result<(), BlobURLStoreError> { let file_impl = self.get_impl(id, origin_in, check_url_validity)?; match file_impl { FileImpl::Memory(buf) => { @@ -423,7 +365,7 @@ impl FileManagerStore { let _ = sender.send(Ok(ReadFileProgress::EOF)); Ok(()) - }, + } FileImpl::MetaDataOnly(metadata) => { /* XXX: Snapshot state check (optional) https://w3c.github.io/FileAPI/#snapshot-state. Concretely, here we create another file, and this file might not @@ -431,62 +373,45 @@ impl FileManagerStore { create_entry is called. */ - let opt_filename = metadata - .path - .file_name() - .and_then(|osstr| osstr.to_str()) - .map(|s| s.to_string()); + let opt_filename = metadata.path.file_name() + .and_then(|osstr| osstr.to_str()) + .map(|s| s.to_string()); let mime = guess_mime_type_opt(metadata.path.clone()); let range = rel_pos.to_abs_range(metadata.size as usize); let mut file = File::open(&metadata.path) - .map_err(|e| BlobURLStoreError::External(e.to_string()))?; - let seeked_start = file - .seek(SeekFrom::Start(range.start as u64)) - .map_err(|e| BlobURLStoreError::External(e.to_string()))?; + .map_err(|e| BlobURLStoreError::External(e.to_string()))?; + let seeked_start = file.seek(SeekFrom::Start(range.start as u64)) + .map_err(|e| BlobURLStoreError::External(e.to_string()))?; if seeked_start == (range.start as u64) { let type_string = match mime { Some(x) => format!("{}", x), - None => "".to_string(), + None => "".to_string(), }; - chunked_read(sender, &mut file, range.len(), opt_filename, type_string); + chunked_read(sender, &mut file, range.len(), opt_filename, + type_string); Ok(()) } else { Err(BlobURLStoreError::InvalidEntry) } - }, + } FileImpl::Sliced(parent_id, inner_rel_pos) => { // Next time we don't need to check validity since // we have already done that for requesting URL if necessary - self.get_blob_buf( - sender, - &parent_id, - origin_in, - rel_pos.slice_inner(&inner_rel_pos), - false, - ) - }, + self.get_blob_buf(sender, &parent_id, origin_in, + rel_pos.slice_inner(&inner_rel_pos), false) + } } } // Convenient wrapper over get_blob_buf - fn try_read_file( - &self, - sender: &IpcSender>, - id: Uuid, - check_url_validity: bool, - origin_in: FileOrigin, - ) -> Result<(), BlobURLStoreError> { - self.get_blob_buf( - sender, - &id, - &origin_in, - RelativePos::full_range(), - check_url_validity, - ) + fn try_read_file(&self, sender: &IpcSender>, + id: Uuid, check_url_validity: bool, origin_in: FileOrigin) + -> Result<(), BlobURLStoreError> { + self.get_blob_buf(sender, &id, &origin_in, RelativePos::full_range(), check_url_validity) } fn dec_ref(&self, id: &Uuid, origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { @@ -511,7 +436,7 @@ impl FileManagerStore { } else { return Err(BlobURLStoreError::InvalidOrigin); } - }, + } None => return Err(BlobURLStoreError::InvalidFileID), }; @@ -529,41 +454,28 @@ impl FileManagerStore { Ok(()) } - fn promote_memory( - &self, - blob_buf: BlobBuf, - set_valid: bool, - sender: IpcSender>, - origin: FileOrigin, - ) { - match Url::parse(&origin) { - // parse to check sanity + fn promote_memory(&self, blob_buf: BlobBuf, set_valid: bool, + sender: IpcSender>, origin: FileOrigin) { + match Url::parse(&origin) { // parse to check sanity Ok(_) => { let id = Uuid::new_v4(); - self.insert( - id, - FileStoreEntry { - origin: origin.clone(), - file_impl: FileImpl::Memory(blob_buf), - refs: AtomicUsize::new(1), - is_valid_url: AtomicBool::new(set_valid), - }, - ); + self.insert(id, FileStoreEntry { + origin: origin.clone(), + file_impl: FileImpl::Memory(blob_buf), + refs: AtomicUsize::new(1), + is_valid_url: AtomicBool::new(set_valid), + }); let _ = sender.send(Ok(id)); - }, + } Err(_) => { let _ = sender.send(Err(BlobURLStoreError::InvalidOrigin)); - }, + } } } - fn set_blob_url_validity( - &self, - validity: bool, - id: &Uuid, - origin_in: &FileOrigin, - ) -> Result<(), BlobURLStoreError> { + fn set_blob_url_validity(&self, validity: bool, id: &Uuid, + origin_in: &FileOrigin) -> Result<(), BlobURLStoreError> { let (do_remove, opt_parent_id, res) = match self.entries.read().unwrap().get(id) { Some(entry) => { if *entry.origin == *origin_in { @@ -573,7 +485,7 @@ impl FileManagerStore { // Check if it is the last possible reference // since refs only accounts for blob id holders // and store entry id holders - let zero_refs = entry.refs.load(Ordering::Acquire) == 0; + let zero_refs = entry.refs.load(Ordering::Acquire) == 0; if let FileImpl::Sliced(ref parent_id, _) = entry.file_impl { (zero_refs, Some(parent_id.clone()), Ok(())) @@ -586,8 +498,8 @@ impl FileManagerStore { } else { (false, None, Err(BlobURLStoreError::InvalidOrigin)) } - }, - None => (false, None, Err(BlobURLStoreError::InvalidFileID)), + } + None => (false, None, Err(BlobURLStoreError::InvalidFileID)) }; if do_remove { @@ -603,21 +515,15 @@ impl FileManagerStore { } fn select_files_pref_enabled() -> bool { - PREFS - .get("dom.testing.htmlinputelement.select_files.enabled") - .as_boolean() - .unwrap_or(false) + PREFS.get("dom.testing.htmlinputelement.select_files.enabled") + .as_boolean().unwrap_or(false) } const CHUNK_SIZE: usize = 8192; -fn chunked_read( - sender: &IpcSender>, - file: &mut File, - size: usize, - opt_filename: Option, - type_string: String, -) { +fn chunked_read(sender: &IpcSender>, + file: &mut File, size: usize, opt_filename: Option, + type_string: String) { // First chunk let mut buf = vec![0; CHUNK_SIZE]; match file.read(&mut buf) { @@ -630,11 +536,11 @@ fn chunked_read( bytes: buf, }; let _ = sender.send(Ok(ReadFileProgress::Meta(blob_buf))); - }, + } Err(e) => { let _ = sender.send(Err(FileManagerThreadError::FileSystemError(e.to_string()))); return; - }, + } } // Send the remaining chunks @@ -644,15 +550,15 @@ fn chunked_read( Ok(0) => { let _ = sender.send(Ok(ReadFileProgress::EOF)); return; - }, + } Ok(n) => { buf.truncate(n); let _ = sender.send(Ok(ReadFileProgress::Partial(buf))); - }, + } Err(e) => { let _ = sender.send(Err(FileManagerThreadError::FileSystemError(e.to_string()))); return; - }, + } } } } diff --git a/components/net/hosts.rs b/components/net/hosts.rs index 52fd5fe671e3..4cc688a474be 100644 --- a/components/net/hosts.rs +++ b/components/net/hosts.rs @@ -31,32 +31,21 @@ pub fn replace_host_table(table: HashMap) { } pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap { - hostsfile_content - .lines() - .filter_map(|line| { - let mut iter = line.split('#').next().unwrap().split_whitespace(); - Some((iter.next()?.parse().ok()?, iter)) + hostsfile_content.lines().filter_map(|line| { + let mut iter = line.split('#').next().unwrap().split_whitespace(); + Some((iter.next()?.parse().ok()?, iter)) + }).flat_map(|(ip, hosts)| { + hosts.filter(|host| { + let invalid = ['\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']']; + host.parse::().is_err() && !host.contains(&invalid[..]) + }).map(move |host| { + (host.to_owned(), ip) }) - .flat_map(|(ip, hosts)| { - hosts - .filter(|host| { - let invalid = [ - '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']', - ]; - host.parse::().is_err() && !host.contains(&invalid[..]) - }) - .map(move |host| (host.to_owned(), ip)) - }) - .collect() + }).collect() } pub fn replace_host(host: &str) -> Cow { - HOST_TABLE - .lock() - .unwrap() - .as_ref() + HOST_TABLE.lock().unwrap().as_ref() .and_then(|table| table.get(host)) - .map_or(host.into(), |replaced_host| { - replaced_host.to_string().into() - }) + .map_or(host.into(), |replaced_host| replaced_host.to_string().into()) } diff --git a/components/net/hsts.rs b/components/net/hsts.rs index 7b1329edbd5d..49d7168e5721 100644 --- a/components/net/hsts.rs +++ b/components/net/hsts.rs @@ -3,26 +3,24 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use embedder_traits::resources::{self, Resource}; -use net_traits::pub_domains::reg_suffix; use net_traits::IncludeSubdomains; +use net_traits::pub_domains::reg_suffix; +use serde_json; use servo_url::ServoUrl; use std::collections::HashMap; use std::net::{Ipv4Addr, Ipv6Addr}; +use time; -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct HstsEntry { pub host: String, pub include_subdomains: bool, pub max_age: Option, - pub timestamp: Option, + pub timestamp: Option } impl HstsEntry { - pub fn new( - host: String, - subdomains: IncludeSubdomains, - max_age: Option, - ) -> Option { + pub fn new(host: String, subdomains: IncludeSubdomains, max_age: Option) -> Option { if host.parse::().is_ok() || host.parse::().is_ok() { None } else { @@ -30,7 +28,7 @@ impl HstsEntry { host: host, include_subdomains: (subdomains == IncludeSubdomains::Included), max_age: max_age, - timestamp: Some(time::get_time().sec as u64), + timestamp: Some(time::get_time().sec as u64) }) } } @@ -39,9 +37,9 @@ impl HstsEntry { match (self.max_age, self.timestamp) { (Some(max_age), Some(timestamp)) => { (time::get_time().sec as u64) - timestamp >= max_age - }, + } - _ => false, + _ => false } } @@ -54,16 +52,14 @@ impl HstsEntry { } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct HstsList { pub entries_map: HashMap>, } impl HstsList { pub fn new() -> HstsList { - HstsList { - entries_map: HashMap::new(), - } + HstsList { entries_map: HashMap::new() } } /// Create an `HstsList` from the bytes of a JSON preload file. @@ -111,9 +107,9 @@ impl HstsList { } fn has_subdomain(&self, host: &str, base_domain: &str) -> bool { - self.entries_map.get(base_domain).map_or(false, |entries| { - entries.iter().any(|e| e.matches_subdomain(host)) - }) + self.entries_map.get(base_domain).map_or(false, |entries| { + entries.iter().any(|e| e.matches_subdomain(host)) + }) } pub fn push(&mut self, entry: HstsEntry) { @@ -122,10 +118,7 @@ impl HstsList { let have_domain = self.has_domain(&entry.host, base_domain); let have_subdomain = self.has_subdomain(&entry.host, base_domain); - let entries = self - .entries_map - .entry(base_domain.to_owned()) - .or_insert(vec![]); + let entries = self.entries_map.entry(base_domain.to_owned()).or_insert(vec![]); if !have_domain && !have_subdomain { entries.push(entry); } else if !have_subdomain { @@ -143,10 +136,7 @@ impl HstsList { if url.scheme() != "http" { return; } - if url - .domain() - .map_or(false, |domain| self.is_host_secure(domain)) - { + if url.domain().map_or(false, |domain| self.is_host_secure(domain)) { url.as_mut_url().set_scheme("https").unwrap(); } } diff --git a/components/net/http_cache.rs b/components/net/http_cache.rs index d467a38baf35..1fcafc929528 100644 --- a/components/net/http_cache.rs +++ b/components/net/http_cache.rs @@ -7,46 +7,46 @@ //! A memory cache implementing the logic specified in //! and . -use crate::fetch::methods::{Data, DoneChannel}; -use headers_core::HeaderMapExt; -use headers_ext::{CacheControl, ContentRange, Expires, LastModified, Pragma, Range, Vary}; -use http::header::HeaderValue; -use http::{header, HeaderMap}; -use hyper::{Method, StatusCode}; +use fetch::methods::{Data, DoneChannel}; +use hyper::header; +use hyper::header::ContentType; +use hyper::header::Headers; +use hyper::method::Method; +use hyper::status::StatusCode; +use hyper_serde::Serde; +use malloc_size_of::{MallocSizeOf, MallocSizeOfOps, MallocUnconditionalSizeOf, MallocUnconditionalShallowSizeOf}; use malloc_size_of::Measurable; -use malloc_size_of::{ - MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf, MallocUnconditionalSizeOf, -}; +use net_traits::{Metadata, FetchMetadata}; use net_traits::request::Request; use net_traits::response::{HttpsState, Response, ResponseBody}; -use net_traits::{FetchMetadata, Metadata}; use servo_arc::Arc; -use servo_channel::{channel, Sender}; +use servo_channel::{Sender, channel}; use servo_config::prefs::PREFS; use servo_url::ServoUrl; use std::collections::HashMap; -use std::ops::Bound; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::str; use std::sync::Mutex; -use std::time::SystemTime; -use time::{Duration, Timespec, Tm}; +use std::sync::atomic::{AtomicBool, Ordering}; +use time; +use time::{Duration, Tm}; + /// The key used to differentiate requests in the cache. -#[derive(Clone, Eq, Hash, MallocSizeOf, PartialEq)] +#[derive(Clone, Eq, Hash, MallocSizeOf, PartialEq )] pub struct CacheKey { - url: ServoUrl, + url: ServoUrl } impl CacheKey { fn new(request: Request) -> CacheKey { CacheKey { - url: request.current_url().clone(), + url: request.current_url().clone() } } fn from_servo_url(servo_url: &ServoUrl) -> CacheKey { CacheKey { - url: servo_url.clone(), + url: servo_url.clone() } } @@ -59,11 +59,11 @@ impl CacheKey { /// A complete cached resource. #[derive(Clone)] struct CachedResource { - request_headers: Arc>, + request_headers: Arc>, body: Arc>, aborted: Arc, awaiting_body: Arc>>>, - data: Measurable, + data: Measurable } #[derive(Clone, MallocSizeOf)] @@ -71,7 +71,7 @@ struct MeasurableCachedResource { metadata: CachedMetadata, location_url: Option>, https_state: HttpsState, - status: Option<(StatusCode, String)>, + status: Option, raw_status: Option<(u16, Vec)>, url_list: Vec, expires: Duration, @@ -80,11 +80,11 @@ struct MeasurableCachedResource { impl MallocSizeOf for CachedResource { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { - // TODO: self.request_headers.unconditional_size_of(ops) + + self.request_headers.unconditional_size_of(ops) + self.body.unconditional_size_of(ops) + - self.aborted.unconditional_size_of(ops) + - self.awaiting_body.unconditional_size_of(ops) + - self.data.size_of(ops) + self.aborted.unconditional_size_of(ops) + + self.awaiting_body.unconditional_size_of(ops) + + self.data.size_of(ops) } } @@ -92,9 +92,9 @@ impl MallocSizeOf for CachedResource { #[derive(Clone)] struct CachedMetadata { /// Headers - pub headers: Arc>, + pub headers: Arc>, /// Fields that implement MallocSizeOf - pub data: Measurable, + pub data: Measurable } #[derive(Clone, MallocSizeOf)] @@ -102,17 +102,17 @@ struct MeasurableCachedMetadata { /// Final URL after redirects. pub final_url: ServoUrl, /// MIME type / subtype. - pub content_type: Option, + pub content_type: Option>, /// Character set. pub charset: Option, /// HTTP Status - pub status: Option<(u16, Vec)>, + pub status: Option<(u16, Vec)> } impl MallocSizeOf for CachedMetadata { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { self.headers.unconditional_shallow_size_of(ops) + - // TODO: self.headers.size_of(ops) + + self.headers.size_of(ops) + self.data.size_of(ops) } } @@ -122,7 +122,7 @@ pub struct CachedResponse { /// The response constructed from the cached resource pub response: Response, /// The revalidation flag for the stored response - pub needs_validation: bool, + pub needs_validation: bool } /// A memory cache. @@ -132,6 +132,7 @@ pub struct HttpCache { entries: HashMap>, } + /// Determine if a given response is cacheable based on the initial metadata received. /// Based on fn response_is_cacheable(metadata: &Metadata) -> bool { @@ -140,28 +141,23 @@ fn response_is_cacheable(metadata: &Metadata) -> bool { // 2. check for absence of the Authorization header field. let mut is_cacheable = false; let headers = metadata.headers.as_ref().unwrap(); - if headers.contains_key(header::EXPIRES) || - headers.contains_key(header::LAST_MODIFIED) || - headers.contains_key(header::ETAG) - { + if headers.has::() || + headers.has::() || + headers.has::() { is_cacheable = true; } - if let Some(ref directive) = headers.typed_get::() { - if directive.no_store() { - return false; - } - if directive.public() || - directive.s_max_age().is_some() || - directive.max_age().is_some() || - directive.no_cache() - { - is_cacheable = true; + if let Some(&header::CacheControl(ref directive)) = headers.get::() { + for directive in directive.iter() { + match *directive { + header::CacheDirective::NoStore => return false, + header::CacheDirective::Public | header::CacheDirective::SMaxAge(_) + | header::CacheDirective::MaxAge(_) | header::CacheDirective::NoCache => is_cacheable = true, + _ => {}, + } } } - if let Some(pragma) = headers.typed_get::() { - if pragma.is_no_cache() { - return false; - } + if let Some(&header::Pragma::NoCache) = headers.get::() { + return false; } is_cacheable } @@ -170,11 +166,10 @@ fn response_is_cacheable(metadata: &Metadata) -> bool { /// fn calculate_response_age(response: &Response) -> Duration { // TODO: follow the spec more closely (Date headers, request/response lag, ...) - if let Some(secs) = response.headers.get(header::AGE) { - if let Ok(seconds_string) = secs.to_str() { - if let Ok(secs) = seconds_string.parse::() { - return Duration::seconds(secs); - } + if let Some(secs) = response.headers.get_raw("Age") { + let seconds_string = String::from_utf8_lossy(&secs[0]); + if let Ok(secs) = seconds_string.parse::() { + return Duration::seconds(secs); } } Duration::seconds(0i64) @@ -185,37 +180,42 @@ fn calculate_response_age(response: &Response) -> Duration { fn get_response_expiry(response: &Response) -> Duration { // Calculating Freshness Lifetime let age = calculate_response_age(&response); - if let Some(directives) = response.headers.typed_get::() { - if directives.no_cache() { + if let Some(&header::CacheControl(ref directives)) = response.headers.get::() { + let has_no_cache_directive = directives.iter().any(|directive| { + header::CacheDirective::NoCache == *directive + }); + if has_no_cache_directive { // Requires validation on first use. return Duration::seconds(0i64); } else { - if let Some(secs) = directives.max_age().or(directives.s_max_age()) { - let max_age = Duration::from_std(secs).unwrap(); - if max_age < age { - return Duration::seconds(0i64); + for directive in directives { + match *directive { + header::CacheDirective::SMaxAge(secs) | header::CacheDirective::MaxAge(secs) => { + let max_age = Duration::seconds(secs as i64); + if max_age < age { + return Duration::seconds(0i64); + } + return max_age - age; + }, + _ => (), } - return max_age - age; } } } - match response.headers.typed_get::() { - Some(t) => { - // store the period of time from now until expiry - let t: SystemTime = t.into(); - let t = t.duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let desired = Timespec::new(t.as_secs() as i64, 0); - let current = time::now().to_timespec(); - - if desired > current { - return desired - current; - } else { - return Duration::seconds(0i64); - } - }, - // Malformed Expires header, shouldn't be used to construct a valid response. - None if response.headers.contains_key(header::EXPIRES) => return Duration::seconds(0i64), - _ => {}, + if let Some(&header::Expires(header::HttpDate(t))) = response.headers.get::() { + // store the period of time from now until expiry + let desired = t.to_timespec(); + let current = time::now().to_timespec(); + if desired > current { + return desired - current; + } else { + return Duration::seconds(0i64); + } + } else { + if let Some(_) = response.headers.get_raw("Expires") { + // Malformed Expires header, shouldn't be used to construct a valid response. + return Duration::seconds(0i64); + } } // Calculating Heuristic Freshness // @@ -224,15 +224,13 @@ fn get_response_expiry(response: &Response) -> Duration { // Since presently we do not generate a Warning header field with a 113 warn-code, // 24 hours minus response age is the max for heuristic calculation. let max_heuristic = Duration::hours(24) - age; - let heuristic_freshness = if let Some(last_modified) = + let heuristic_freshness = if let Some(&header::LastModified(header::HttpDate(t))) = // If the response has a Last-Modified header field, // caches are encouraged to use a heuristic expiration value // that is no more than some fraction of the interval since that time. - response.headers.typed_get::() { + response.headers.get::() { + let last_modified = t.to_timespec(); let current = time::now().to_timespec(); - let last_modified: SystemTime = last_modified.into(); - let last_modified = last_modified.duration_since(SystemTime::UNIX_EPOCH).unwrap(); - let last_modified = Timespec::new(last_modified.as_secs() as i64, 0); // A typical setting of this fraction might be 10%. let raw_heuristic_calc = (current - last_modified) / 10; let result = if raw_heuristic_calc < max_heuristic { @@ -247,12 +245,15 @@ fn get_response_expiry(response: &Response) -> Duration { match *code { 200 | 203 | 204 | 206 | 300 | 301 | 404 | 405 | 410 | 414 | 501 => { // Status codes that are cacheable by default - return heuristic_freshness; + return heuristic_freshness }, _ => { // Other status codes can only use heuristic freshness if the public cache directive is present. - if let Some(ref directives) = response.headers.typed_get::() { - if directives.public() { + if let Some(&header::CacheControl(ref directives)) = response.headers.get::() { + let has_public_directive = directives.iter().any(|directive| { + header::CacheDirective::Public == *directive + }); + if has_public_directive { return heuristic_freshness; } } @@ -266,53 +267,57 @@ fn get_response_expiry(response: &Response) -> Duration { /// Request Cache-Control Directives /// fn get_expiry_adjustment_from_request_headers(request: &Request, expires: Duration) -> Duration { - let directive = match request.headers.typed_get::() { + let directive_data = match request.headers.get_raw("cache-control") { Some(data) => data, None => return expires, }; - - if let Some(max_age) = directive.max_stale() { - return expires + Duration::from_std(max_age).unwrap(); - } - if let Some(max_age) = directive.max_age() { - let max_age = Duration::from_std(max_age).unwrap(); - if expires > max_age { - return Duration::min_value(); - } - return expires - max_age; - } - if let Some(min_fresh) = directive.min_fresh() { - let min_fresh = Duration::from_std(min_fresh).unwrap(); - if expires < min_fresh { - return Duration::min_value(); + let directives_string = String::from_utf8_lossy(&directive_data[0]); + for directive in directives_string.split(",") { + let mut directive_info = directive.split("="); + match (directive_info.next(), directive_info.next()) { + (Some("max-stale"), Some(sec_str)) => { + if let Ok(secs) = sec_str.parse::() { + return expires + Duration::seconds(secs); + } + }, + (Some("max-age"), Some(sec_str)) => { + if let Ok(secs) = sec_str.parse::() { + let max_age = Duration::seconds(secs); + if expires > max_age { + return Duration::min_value(); + } + return expires - max_age; + } + }, + (Some("min-fresh"), Some(sec_str)) => { + if let Ok(secs) = sec_str.parse::() { + let min_fresh = Duration::seconds(secs); + if expires < min_fresh { + return Duration::min_value(); + } + return expires - min_fresh; + } + }, + (Some("no-cache"), _) | (Some("no-store"), _) => return Duration::min_value(), + _ => {} } - return expires - min_fresh; } - if directive.no_cache() || directive.no_store() { - return Duration::min_value(); - } - expires } /// Create a CachedResponse from a request and a CachedResource. -fn create_cached_response( - request: &Request, +fn create_cached_response(request: &Request, cached_resource: &CachedResource, - cached_headers: &HeaderMap, - done_chan: &mut DoneChannel, -) -> CachedResponse { + cached_headers: &Headers, + done_chan: &mut DoneChannel) + -> CachedResponse { let mut response = Response::new(cached_resource.data.metadata.data.final_url.clone()); response.headers = cached_headers.clone(); response.body = cached_resource.body.clone(); if let ResponseBody::Receiving(_) = *cached_resource.body.lock().unwrap() { let (done_sender, done_receiver) = channel(); *done_chan = Some((done_sender.clone(), done_receiver)); - cached_resource - .awaiting_body - .lock() - .unwrap() - .push(done_sender); + cached_resource.awaiting_body.lock().unwrap().push(done_sender); } response.location_url = cached_resource.data.location_url.clone(); response.status = cached_resource.data.status.clone(); @@ -330,20 +335,15 @@ fn create_cached_response( // TODO: take must-revalidate into account // TODO: if this cache is to be considered shared, take proxy-revalidate into account // - let has_expired = - (adjusted_expires < time_since_validated) || (adjusted_expires == time_since_validated); - CachedResponse { - response: response, - needs_validation: has_expired, - } + let has_expired = (adjusted_expires < time_since_validated) || + (adjusted_expires == time_since_validated); + CachedResponse { response: response, needs_validation: has_expired } } /// Create a new resource, based on the bytes requested, and an existing resource, /// with a status-code of 206. -fn create_resource_with_bytes_from_resource( - bytes: &[u8], - resource: &CachedResource, -) -> CachedResource { +fn create_resource_with_bytes_from_resource(bytes: &[u8], resource: &CachedResource) + -> CachedResource { CachedResource { request_headers: resource.request_headers.clone(), body: Arc::new(Mutex::new(ResponseBody::Done(bytes.to_owned()))), @@ -353,40 +353,34 @@ fn create_resource_with_bytes_from_resource( metadata: resource.data.metadata.clone(), location_url: resource.data.location_url.clone(), https_state: resource.data.https_state.clone(), - status: Some((StatusCode::PARTIAL_CONTENT, "Partial Content".into())), + status: Some(StatusCode::PartialContent), raw_status: Some((206, b"Partial Content".to_vec())), url_list: resource.data.url_list.clone(), expires: resource.data.expires.clone(), last_validated: resource.data.last_validated.clone(), - }), + }) } } /// Support for range requests . -fn handle_range_request( - request: &Request, +fn handle_range_request(request: &Request, candidates: Vec<&CachedResource>, - range_spec: Vec<(Bound, Bound)>, - done_chan: &mut DoneChannel, -) -> Option { - let mut complete_cached_resources = - candidates - .iter() - .filter(|resource| match resource.data.raw_status { - Some((ref code, _)) => *code == 200, - None => false, - }); - let partial_cached_resources = - candidates - .iter() - .filter(|resource| match resource.data.raw_status { - Some((ref code, _)) => *code == 206, - None => false, - }); - match ( - range_spec.first().unwrap(), - complete_cached_resources.next(), - ) { + range_spec: &[header::ByteRangeSpec], + done_chan: &mut DoneChannel) + -> Option { + let mut complete_cached_resources = candidates.iter().filter(|resource| { + match resource.data.raw_status { + Some((ref code, _)) => *code == 200, + None => false + } + }); + let partial_cached_resources = candidates.iter().filter(|resource| { + match resource.data.raw_status { + Some((ref code, _)) => *code == 206, + None => false + } + }); + match (range_spec.first().unwrap(), complete_cached_resources.next()) { // TODO: take the full range spec into account. // If we have a complete resource, take the request range from the body. // When there isn't a complete resource available, we loop over cached partials, @@ -395,33 +389,27 @@ fn handle_range_request( // see . // TODO: add support for complete and partial resources, // whose body is in the ResponseBody::Receiving state. - (&(Bound::Included(beginning), Bound::Included(end)), Some(ref complete_resource)) => { + (&header::ByteRangeSpec::FromTo(beginning, end), Some(ref complete_resource)) => { if let ResponseBody::Done(ref body) = *complete_resource.body.lock().unwrap() { let b = beginning as usize; let e = end as usize + 1; let requested = body.get(b..e); if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = - create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } }, - (&(Bound::Included(beginning), Bound::Included(end)), None) => { + (&header::ByteRangeSpec::FromTo(beginning, end), None) => { for partial_resource in partial_cached_resources { let headers = partial_resource.data.metadata.headers.lock().unwrap(); - let content_range = headers.typed_get::(); + let content_range = headers.get::(); let (res_beginning, res_end) = match content_range { - Some(range) => { - if let Some(bytes_range) = range.bytes_range() { - bytes_range - } else { - continue; - } - }, + Some(&header::ContentRange( + header::ContentRangeSpec::Bytes { + range: Some((res_beginning, res_end)), .. })) => (res_beginning, res_end), _ => continue, }; if res_beginning - 1 < beginning && res_end + 1 > end { @@ -435,40 +423,35 @@ fn handle_range_request( _ => continue, }; if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = - create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } } }, - (&(Bound::Included(beginning), Bound::Unbounded), Some(ref complete_resource)) => { + (&header::ByteRangeSpec::AllFrom(beginning), Some(ref complete_resource)) => { if let ResponseBody::Done(ref body) = *complete_resource.body.lock().unwrap() { let b = beginning as usize; let requested = body.get(b..); if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = - create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } }, - (&(Bound::Included(beginning), Bound::Unbounded), None) => { + (&header::ByteRangeSpec::AllFrom(beginning), None) => { for partial_resource in partial_cached_resources { let headers = partial_resource.data.metadata.headers.lock().unwrap(); - let content_range = headers.typed_get::(); - let (res_beginning, res_end, total) = if let Some(range) = content_range { - match (range.bytes_range(), range.bytes_len()) { - (Some(bytes_range), Some(total)) => (bytes_range.0, bytes_range.1, total), - _ => continue, - } - } else { - continue; + let content_range = headers.get::(); + let (res_beginning, res_end, total) = match content_range { + Some(&header::ContentRange( + header::ContentRangeSpec::Bytes { + range: Some((res_beginning, res_end)), + instance_length: Some(total) })) => (res_beginning, res_end, total), + _ => continue, }; if res_beginning < beginning && res_end == total - 1 { let resource_body = &*partial_resource.body.lock().unwrap(); @@ -480,42 +463,37 @@ fn handle_range_request( _ => continue, }; if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = - create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } } }, - (&(Bound::Unbounded, Bound::Included(offset)), Some(ref complete_resource)) => { + (&header::ByteRangeSpec::Last(offset), Some(ref complete_resource)) => { if let ResponseBody::Done(ref body) = *complete_resource.body.lock().unwrap() { let from_byte = body.len() - offset as usize; let requested = body.get(from_byte..); if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(bytes, complete_resource); + let new_resource = create_resource_with_bytes_from_resource(bytes, complete_resource); let cached_headers = new_resource.data.metadata.headers.lock().unwrap(); - let cached_response = - create_cached_response(request, &new_resource, &*cached_headers, done_chan); + let cached_response = create_cached_response(request, &new_resource, &*cached_headers, done_chan); return Some(cached_response); } } }, - (&(Bound::Unbounded, Bound::Included(offset)), None) => { + (&header::ByteRangeSpec::Last(offset), None) => { for partial_resource in partial_cached_resources { let headers = partial_resource.data.metadata.headers.lock().unwrap(); - let content_range = headers.typed_get::(); - let (res_beginning, res_end, total) = if let Some(range) = content_range { - match (range.bytes_range(), range.bytes_len()) { - (Some(bytes_range), Some(total)) => (bytes_range.0, bytes_range.1, total), - _ => continue, - } - } else { - continue; + let content_range = headers.get::(); + let (res_beginning, res_end, total) = match content_range { + Some(&header::ContentRange( + header::ContentRangeSpec::Bytes { + range: Some((res_beginning, res_end)), + instance_length: Some(total) })) => (res_beginning, res_end, total), + _ => continue, }; - if (total - res_beginning) > (offset - 1) && (total - res_end) < offset + 1 { + if (total - res_beginning) > (offset - 1 ) && (total - res_end) < offset + 1 { let resource_body = &*partial_resource.body.lock().unwrap(); let requested = match resource_body { &ResponseBody::Done(ref body) => { @@ -525,84 +503,76 @@ fn handle_range_request( _ => continue, }; if let Some(bytes) = requested { - let new_resource = - create_resource_with_bytes_from_resource(&bytes, partial_resource); - let cached_response = - create_cached_response(request, &new_resource, &*headers, done_chan); + let new_resource = create_resource_with_bytes_from_resource(&bytes, partial_resource); + let cached_response = create_cached_response(request, &new_resource, &*headers, done_chan); return Some(cached_response); } } } - }, - // All the cases with Bound::Excluded should be unreachable anyway - _ => return None, + } } None } + impl HttpCache { /// Create a new memory cache instance. pub fn new() -> HttpCache { HttpCache { - entries: HashMap::new(), + entries: HashMap::new() } } /// Constructing Responses from Caches. /// - pub fn construct_response( - &self, - request: &Request, - done_chan: &mut DoneChannel, - ) -> Option { + pub fn construct_response(&self, request: &Request, done_chan: &mut DoneChannel) -> Option { // TODO: generate warning headers as appropriate - if request.method != Method::GET { + if request.method != Method::Get { // Only Get requests are cached, avoid a url based match for others. return None; } let entry_key = CacheKey::new(request.clone()); - let resources = self - .entries - .get(&entry_key)? - .into_iter() - .filter(|r| !r.aborted.load(Ordering::Relaxed)); + let resources = self.entries.get(&entry_key)?.into_iter().filter(|r| { !r.aborted.load(Ordering::Relaxed) }); let mut candidates = vec![]; for cached_resource in resources { let mut can_be_constructed = true; let cached_headers = cached_resource.data.metadata.headers.lock().unwrap(); let original_request_headers = cached_resource.request_headers.lock().unwrap(); - if let Some(vary_value) = cached_headers.typed_get::() { - if vary_value.is_any() { - can_be_constructed = false - } else { + if let Some(vary_data) = cached_headers.get_raw("Vary") { + // Calculating Secondary Keys with Vary + let vary_data_string = String::from_utf8_lossy(&vary_data[0]); + let vary_values = vary_data_string.split(",").map(|val| val.trim()); + for vary_val in vary_values { // For every header name found in the Vary header of the stored response. - // Calculating Secondary Keys with Vary - for vary_val in vary_value.iter_strs() { - match request.headers.get(vary_val) { - Some(header_data) => { - // If the header is present in the request. - if let Some(original_header_data) = - original_request_headers.get(vary_val) - { - // Check that the value of the nominated header field, - // in the original request, matches the value in the current request. - if original_header_data != header_data { - can_be_constructed = false; - break; - } + if vary_val == "*" { + // A Vary header field-value of "*" always fails to match. + can_be_constructed = false; + break; + } + match request.headers.get_raw(vary_val) { + Some(header_data) => { + // If the header is present in the request. + let request_header_data_string = String::from_utf8_lossy(&header_data[0]); + if let Some(original_header_data) = original_request_headers.get_raw(vary_val) { + // Check that the value of the nominated header field, + // in the original request, matches the value in the current request. + let original_request_header_data_string = + String::from_utf8_lossy(&original_header_data[0]); + if original_request_header_data_string != request_header_data_string { + can_be_constructed = false; + break; } - }, - None => { - // If a header field is absent from a request, - // it can only match a stored response if those headers, - // were also absent in the original request. - can_be_constructed = - original_request_headers.get(vary_val).is_none(); - }, - } - if !can_be_constructed { - break; - } + } + }, + None => { + // If a header field is absent from a request, + // it can only match a stored response if those headers, + // were also absent in the original request. + can_be_constructed = original_request_headers.get_raw(vary_val).is_none(); + }, + } + if !can_be_constructed { + break; } } } @@ -611,13 +581,8 @@ impl HttpCache { } } // Support for range requests - if let Some(range_spec) = request.headers.typed_get::() { - return handle_range_request( - request, - candidates, - range_spec.iter().collect(), - done_chan, - ); + if let Some(&header::Range::Bytes(ref range_spec)) = request.headers.get::() { + return handle_range_request(request, candidates, &range_spec, done_chan); } else { // Not a Range request. if let Some(ref cached_resource) = candidates.first() { @@ -625,8 +590,7 @@ impl HttpCache { // TODO: select the most appropriate one, using a known mechanism from a selecting header field, // or using the Date header to return the most recent one. let cached_headers = cached_resource.data.metadata.headers.lock().unwrap(); - let cached_response = - create_cached_response(request, cached_resource, &*cached_headers, done_chan); + let cached_response = create_cached_response(request, cached_resource, &*cached_headers, done_chan); return Some(cached_response); } } @@ -647,7 +611,7 @@ impl HttpCache { let _ = done_sender.send(Data::Payload(completed_body.clone())); let _ = done_sender.send(Data::Done); } - } + }; } } } @@ -655,13 +619,8 @@ impl HttpCache { /// Freshening Stored Responses upon Validation. /// - pub fn refresh( - &mut self, - request: &Request, - response: Response, - done_chan: &mut DoneChannel, - ) -> Option { - assert_eq!(response.status.map(|s| s.0), Some(StatusCode::NOT_MODIFIED)); + pub fn refresh(&mut self, request: &Request, response: Response, done_chan: &mut DoneChannel) -> Option { + assert_eq!(response.status, Some(StatusCode::NotModified)); let entry_key = CacheKey::new(request.clone()); if let Some(cached_resources) = self.entries.get_mut(&entry_key) { for cached_resource in cached_resources.iter_mut() { @@ -670,25 +629,22 @@ impl HttpCache { // Otherwise, create a new dedicated channel to update the consumer. // The response constructed here will replace the 304 one from the network. let in_progress_channel = match *cached_resource.body.lock().unwrap() { - ResponseBody::Receiving(..) => Some(channel()), - ResponseBody::Empty | ResponseBody::Done(..) => None, + ResponseBody::Receiving(..) => { + Some(channel()) + }, + ResponseBody::Empty | ResponseBody::Done(..) => None }; match in_progress_channel { Some((done_sender, done_receiver)) => { *done_chan = Some((done_sender.clone(), done_receiver)); - cached_resource - .awaiting_body - .lock() - .unwrap() - .push(done_sender); + cached_resource.awaiting_body.lock().unwrap().push(done_sender); }, - None => *done_chan = None, + None => *done_chan = None } // Received a response with 304 status code, in response to a request that matches a cached resource. // 1. update the headers of the cached resource. // 2. return a response, constructed from the cached resource. - let mut constructed_response = - Response::new(cached_resource.data.metadata.data.final_url.clone()); + let mut constructed_response = Response::new(cached_resource.data.metadata.data.final_url.clone()); constructed_response.body = cached_resource.body.clone(); constructed_response.status = cached_resource.data.status.clone(); constructed_response.https_state = cached_resource.data.https_state.clone(); @@ -698,7 +654,7 @@ impl HttpCache { constructed_response.url_list = cached_resource.data.url_list.clone(); cached_resource.data.expires = get_response_expiry(&constructed_response); let mut stored_headers = cached_resource.data.metadata.headers.lock().unwrap(); - stored_headers.extend(response.headers); + stored_headers.extend(response.headers.iter()); constructed_response.headers = stored_headers.clone(); return Some(constructed_response); } @@ -718,23 +674,17 @@ impl HttpCache { /// Invalidation. /// pub fn invalidate(&mut self, request: &Request, response: &Response) { - // TODO(eijebong): Once headers support typed_get, update this to use them - if let Some(Ok(location)) = response - .headers - .get(header::LOCATION) - .map(HeaderValue::to_str) - { + if let Some(&header::Location(ref location)) = response.headers.get::() { if let Ok(url) = request.current_url().join(location) { self.invalidate_for_url(&url); } } - if let Some(Ok(ref content_location)) = response - .headers - .get(header::CONTENT_LOCATION) - .map(HeaderValue::to_str) - { - if let Ok(url) = request.current_url().join(&content_location) { - self.invalidate_for_url(&url); + // TODO: update hyper to use typed getter. + if let Some(url_data) = response.headers.get_raw("Content-Location") { + if let Ok(content_location) = str::from_utf8(&url_data[0]) { + if let Ok(url) = request.current_url().join(content_location) { + self.invalidate_for_url(&url); + } } } self.invalidate_for_url(&request.url()); @@ -743,23 +693,18 @@ impl HttpCache { /// Storing Responses in Caches. /// pub fn store(&mut self, request: &Request, response: &Response) { - if PREFS - .get("network.http-cache.disabled") - .as_boolean() - .unwrap_or(false) - { - return; + if PREFS.get("network.http-cache.disabled").as_boolean().unwrap_or(false) { + return } - if request.method != Method::GET { + if request.method != Method::Get { // Only Get requests are cached. - return; + return } let entry_key = CacheKey::new(request.clone()); let metadata = match response.metadata() { Ok(FetchMetadata::Filtered { - filtered: _, - unsafe_: metadata, - }) | + filtered: _, + unsafe_: metadata }) | Ok(FetchMetadata::Unfiltered(metadata)) => metadata, _ => return, }; @@ -771,10 +716,10 @@ impl HttpCache { headers: Arc::new(Mutex::new(response.headers.clone())), data: Measurable(MeasurableCachedMetadata { final_url: metadata.final_url, - content_type: metadata.content_type.map(|v| v.0.to_string()), + content_type: metadata.content_type, charset: metadata.charset, - status: metadata.status, - }), + status: metadata.status + }) }; let entry_resource = CachedResource { request_headers: Arc::new(Mutex::new(request.headers.clone())), @@ -789,10 +734,11 @@ impl HttpCache { raw_status: response.raw_status.clone(), url_list: response.url_list.clone(), expires: expiry, - last_validated: time::now(), - }), + last_validated: time::now() + }) }; let entry = self.entries.entry(entry_key).or_insert(vec![]); entry.push(entry_resource); } + } diff --git a/components/net/http_loader.rs b/components/net/http_loader.rs index ab1de55a1c97..fe85fc5a6f73 100644 --- a/components/net/http_loader.rs +++ b/components/net/http_loader.rs @@ -3,65 +3,69 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use brotli::Decompressor; -use bytes::Bytes; -use crate::connector::{create_http_client, Connector, WrappedBody, BUF_SIZE}; -use crate::cookie; -use crate::cookie_storage::CookieStorage; -use crate::fetch::cors_cache::CorsCache; -use crate::fetch::methods::{ - is_cors_safelisted_method, is_cors_safelisted_request_header, main_fetch, -}; -use crate::fetch::methods::{Data, DoneChannel, FetchContext, Target}; -use crate::hsts::HstsList; -use crate::http_cache::HttpCache; -use crate::resource_thread::AuthCache; -use devtools_traits::{ - ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest, -}; +use connector::{Connector, create_http_connector}; +use cookie; +use cookie_storage::CookieStorage; +use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, HttpRequest as DevtoolsHttpRequest}; use devtools_traits::{HttpResponse as DevtoolsHttpResponse, NetworkEvent}; +use fetch::cors_cache::CorsCache; +use fetch::methods::{Data, DoneChannel, FetchContext, Target}; +use fetch::methods::{is_cors_safelisted_request_header, is_cors_safelisted_method, main_fetch}; use flate2::read::{DeflateDecoder, GzDecoder}; -use headers_core::HeaderMapExt; -use headers_ext::{AccessControlAllowCredentials, AccessControlAllowHeaders}; -use headers_ext::{ - AccessControlAllowMethods, AccessControlRequestHeaders, AccessControlRequestMethod, - Authorization, -}; -use headers_ext::{AccessControlAllowOrigin, AccessControlMaxAge, Basic}; -use headers_ext::{CacheControl, ContentEncoding, ContentLength}; -use headers_ext::{ - Host, IfModifiedSince, LastModified, Origin as HyperOrigin, Pragma, Referer, UserAgent, -}; -use http::header::{self, HeaderName, HeaderValue}; -use http::uri::Authority; -use http::{HeaderMap, Request as HyperRequest}; -use hyper::{Body, Client, Method, Response as HyperResponse, StatusCode}; +use hsts::HstsList; +use http_cache::HttpCache; +use hyper::Error as HttpError; +use hyper::LanguageTag; +use hyper::client::{Pool, Request as HyperRequest, Response as HyperResponse}; +use hyper::header::{Accept, AccessControlAllowCredentials, AccessControlAllowHeaders}; +use hyper::header::{AccessControlAllowMethods, AccessControlAllowOrigin}; +use hyper::header::{AccessControlMaxAge, AccessControlRequestHeaders}; +use hyper::header::{AccessControlRequestMethod, AcceptEncoding, AcceptLanguage}; +use hyper::header::{Authorization, Basic, CacheControl, CacheDirective}; +use hyper::header::{ContentEncoding, ContentLength, Encoding, Header, Headers}; +use hyper::header::{Host, HttpDate, Origin as HyperOrigin, IfMatch, IfRange}; +use hyper::header::{IfUnmodifiedSince, IfModifiedSince, IfNoneMatch, Location}; +use hyper::header::{Pragma, Quality, QualityItem, Referer, SetCookie}; +use hyper::header::{UserAgent, q, qitem}; +use hyper::method::Method; +use hyper::status::StatusCode; +use hyper_openssl::OpensslClient; use hyper_serde::Serde; +use log; use msg::constellation_msg::{HistoryStateId, PipelineId}; -use net_traits::quality::{quality_to_value, Quality, QualityItem}; +use net_traits::{CookieSource, FetchMetadata, NetworkError, ReferrerPolicy}; use net_traits::request::{CacheMode, CredentialsMode, Destination, Origin}; use net_traits::request::{RedirectMode, Referrer, Request, RequestMode}; use net_traits::request::{ResponseTainting, ServiceWorkersMode}; use net_traits::response::{HttpsState, Response, ResponseBody, ResponseType}; -use net_traits::{CookieSource, FetchMetadata, NetworkError, ReferrerPolicy}; -use openssl::ssl::SslConnectorBuilder; +use resource_thread::AuthCache; use servo_channel::{channel, Sender}; use servo_url::{ImmutableOrigin, ServoUrl}; use std::collections::{HashMap, HashSet}; use std::error::Error; -use std::io::Cursor; +use std::io::{self, Read, Write}; use std::iter::FromIterator; use std::mem; use std::ops::Deref; use std::str::FromStr; -use std::sync::Mutex; use std::sync::RwLock; -use std::time::{Duration, SystemTime}; -use time::{self, Tm}; -use tokio::prelude::{future, Future, Stream}; -use tokio::runtime::Runtime; - -lazy_static! { - pub static ref HANDLE: Mutex = { Mutex::new(Runtime::new().unwrap()) }; +use std::thread; +use time; +use time::Tm; +use unicase::UniCase; +use uuid; + +fn read_block(reader: &mut R) -> Result { + let mut buf = vec![0; 32768]; + + match reader.read(&mut buf) { + Ok(len) if len > 0 => { + buf.truncate(len); + Ok(Data::Payload(buf)) + } + Ok(_) => Ok(Data::Done), + Err(_) => Err(()), + } } pub struct HttpState { @@ -70,18 +74,20 @@ pub struct HttpState { pub http_cache: RwLock, pub auth_cache: RwLock, pub history_states: RwLock>>, - pub client: Client, + pub ssl_client: OpensslClient, + pub connector: Pool, } impl HttpState { - pub fn new(ssl_connector_builder: SslConnectorBuilder) -> HttpState { + pub fn new(ssl_client: OpensslClient) -> HttpState { HttpState { hsts_list: RwLock::new(HstsList::new()), cookie_jar: RwLock::new(CookieStorage::new(150)), auth_cache: RwLock::new(AuthCache::new()), history_states: RwLock::new(HashMap::new()), http_cache: RwLock::new(HttpCache::new()), - client: create_http_client(ssl_connector_builder, HANDLE.lock().unwrap().executor()), + ssl_client: ssl_client.clone(), + connector: create_http_connector(ssl_client), } } } @@ -91,64 +97,72 @@ fn precise_time_ms() -> u64 { } // Step 3 of https://fetch.spec.whatwg.org/#concept-fetch. -pub fn set_default_accept(destination: Destination, headers: &mut HeaderMap) { - if headers.contains_key(header::ACCEPT) { +pub fn set_default_accept(destination: Destination, headers: &mut Headers) { + if headers.has::() { return; } let value = match destination { // Step 3.2. - Destination::Document => vec![ - QualityItem::new(mime::TEXT_HTML, Quality::from_u16(1000)), - QualityItem::new( - "application/xhtml+xml".parse().unwrap(), - Quality::from_u16(1000), - ), - QualityItem::new("application/xml".parse().unwrap(), Quality::from_u16(900)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(800)), - ], + Destination::Document => { + vec![ + qitem(mime!(Text / Html)), + qitem(mime!(Application / ("xhtml+xml"))), + QualityItem::new(mime!(Application / Xml), q(0.9)), + QualityItem::new(mime!(_ / _), q(0.8)), + ] + }, // Step 3.3. - Destination::Image => vec![ - QualityItem::new(mime::IMAGE_PNG, Quality::from_u16(1000)), - QualityItem::new(mime::IMAGE_SVG, Quality::from_u16(1000)), - QualityItem::new(mime::IMAGE_STAR, Quality::from_u16(800)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(500)), - ], + Destination::Image => { + vec![ + qitem(mime!(Image / Png)), + qitem(mime!(Image / ("svg+xml") )), + QualityItem::new(mime!(Image / _), q(0.8)), + QualityItem::new(mime!(_ / _), q(0.5)), + ] + }, // Step 3.3. - Destination::Style => vec![ - QualityItem::new(mime::TEXT_CSS, Quality::from_u16(1000)), - QualityItem::new(mime::STAR_STAR, Quality::from_u16(100)), - ], + Destination::Style => { + vec![ + qitem(mime!(Text / Css)), + QualityItem::new(mime!(_ / _), q(0.1)) + ] + }, // Step 3.1. - _ => vec![QualityItem::new(mime::STAR_STAR, Quality::from_u16(1000))], + _ => { + vec![qitem(mime!(_ / _))] + }, }; // Step 3.4. - // TODO(eijebong): Change this once typed headers are done - headers.insert(header::ACCEPT, quality_to_value(value)); + headers.set(Accept(value)); } -fn set_default_accept_encoding(headers: &mut HeaderMap) { - if headers.contains_key(header::ACCEPT_ENCODING) { - return; +fn set_default_accept_encoding(headers: &mut Headers) { + if headers.has::() { + return } - // TODO(eijebong): Change this once typed headers are done - headers.insert( - header::ACCEPT_ENCODING, - HeaderValue::from_static("gzip, deflate, br"), - ); + headers.set(AcceptEncoding(vec![ + qitem(Encoding::Gzip), + qitem(Encoding::Deflate), + qitem(Encoding::EncodingExt("br".to_owned())) + ])); } -pub fn set_default_accept_language(headers: &mut HeaderMap) { - if headers.contains_key(header::ACCEPT_LANGUAGE) { +pub fn set_default_accept_language(headers: &mut Headers) { + if headers.has::() { return; } - // TODO(eijebong): Change this once typed headers are done - headers.insert( - header::ACCEPT_LANGUAGE, - HeaderValue::from_static("en-US, en; q=0.5"), - ); + let mut en_us: LanguageTag = Default::default(); + en_us.language = Some("en".to_owned()); + en_us.region = Some("US".to_owned()); + let mut en: LanguageTag = Default::default(); + en.language = Some("en".to_owned()); + headers.set(AcceptLanguage(vec![ + qitem(en_us), + QualityItem::new(en, Quality(500)), + ])); } /// @@ -196,13 +210,12 @@ fn strip_url(mut referrer_url: ServoUrl, origin_only: bool) -> Option /// /// Steps 4-6. -pub fn determine_request_referrer( - headers: &mut HeaderMap, - referrer_policy: ReferrerPolicy, - referrer_source: ServoUrl, - current_url: ServoUrl, -) -> Option { - assert!(!headers.contains_key(header::REFERER)); +pub fn determine_request_referrer(headers: &mut Headers, + referrer_policy: ReferrerPolicy, + referrer_source: ServoUrl, + current_url: ServoUrl) + -> Option { + assert!(!headers.has::()); // FIXME(#14505): this does not seem to be the correct way of checking for // same-origin requests. let cross_origin = referrer_source.origin() != current_url.origin(); @@ -211,97 +224,109 @@ pub fn determine_request_referrer( match referrer_policy { ReferrerPolicy::NoReferrer => None, ReferrerPolicy::Origin => strip_url(referrer_source, true), - ReferrerPolicy::SameOrigin => { - if cross_origin { - None - } else { - strip_url(referrer_source, false) - } - }, + ReferrerPolicy::SameOrigin => if cross_origin { None } else { strip_url(referrer_source, false) }, ReferrerPolicy::UnsafeUrl => strip_url(referrer_source, false), ReferrerPolicy::OriginWhenCrossOrigin => strip_url(referrer_source, cross_origin), ReferrerPolicy::StrictOrigin => strict_origin(referrer_source, current_url), - ReferrerPolicy::StrictOriginWhenCrossOrigin => { - strict_origin_when_cross_origin(referrer_source, current_url) - }, - ReferrerPolicy::NoReferrerWhenDowngrade => { - no_referrer_when_downgrade_header(referrer_source, current_url) - }, + ReferrerPolicy::StrictOriginWhenCrossOrigin => strict_origin_when_cross_origin(referrer_source, current_url), + ReferrerPolicy::NoReferrerWhenDowngrade => no_referrer_when_downgrade_header(referrer_source, current_url), } } -pub fn set_request_cookies( - url: &ServoUrl, - headers: &mut HeaderMap, - cookie_jar: &RwLock, -) { +pub fn set_request_cookies(url: &ServoUrl, headers: &mut Headers, cookie_jar: &RwLock) { let mut cookie_jar = cookie_jar.write().unwrap(); if let Some(cookie_list) = cookie_jar.cookies_for_url(url, CookieSource::HTTP) { - headers.insert( - header::COOKIE, - HeaderValue::from_bytes(cookie_list.as_bytes()).unwrap(), - ); + let mut v = Vec::new(); + v.push(cookie_list.into_bytes()); + headers.set_raw("Cookie".to_owned(), v); } } -fn set_cookie_for_url(cookie_jar: &RwLock, request: &ServoUrl, cookie_val: &str) { +fn set_cookie_for_url(cookie_jar: &RwLock, + request: &ServoUrl, + cookie_val: String) { let mut cookie_jar = cookie_jar.write().unwrap(); let source = CookieSource::HTTP; + let header = Header::parse_header(&[cookie_val.into_bytes()]); - if let Some(cookie) = cookie::Cookie::from_cookie_string(cookie_val.into(), request, source) { - cookie_jar.push(cookie, request, source); + if let Ok(SetCookie(cookies)) = header { + for cookie in cookies { + if let Some(cookie) = cookie::Cookie::from_cookie_string(cookie, request, source) { + cookie_jar.push(cookie, request, source); + } + } } } -fn set_cookies_from_headers( - url: &ServoUrl, - headers: &HeaderMap, - cookie_jar: &RwLock, -) { - for cookie in headers.get_all(header::SET_COOKIE) { - if let Ok(cookie_str) = cookie.to_str() { - set_cookie_for_url(&cookie_jar, &url, &cookie_str); +fn set_cookies_from_headers(url: &ServoUrl, headers: &Headers, cookie_jar: &RwLock) { + if let Some(cookies) = headers.get_raw("set-cookie") { + for cookie in cookies.iter() { + if let Ok(cookie_value) = String::from_utf8(cookie.clone()) { + set_cookie_for_url(&cookie_jar, + &url, + cookie_value); + } } } } -impl Decoder { - fn from_http_response(response: &HyperResponse) -> Decoder { - if let Some(encoding) = response.headers().typed_get::() { - if encoding.contains("gzip") { - Decoder::Gzip(None) - } else if encoding.contains("deflate") { - Decoder::Deflate(DeflateDecoder::new(Cursor::new(Bytes::new()))) - } else if encoding.contains("br") { - Decoder::Brotli(Decompressor::new(Cursor::new(Bytes::new()), BUF_SIZE)) +struct StreamedResponse { + decoder: Decoder, +} + + +impl Read for StreamedResponse { + #[inline] + fn read(&mut self, buf: &mut [u8]) -> io::Result { + match self.decoder { + Decoder::Gzip(ref mut d) => d.read(buf), + Decoder::Deflate(ref mut d) => d.read(buf), + Decoder::Brotli(ref mut d) => d.read(buf), + Decoder::Plain(ref mut d) => d.read(buf) + } + } +} + +impl StreamedResponse { + fn from_http_response(response: HyperResponse) -> io::Result { + let decoder = { + if let Some(ref encoding) = response.headers.get::().cloned() { + if encoding.contains(&Encoding::Gzip) { + Decoder::Gzip(GzDecoder::new(response)) + } + else if encoding.contains(&Encoding::Deflate) { + Decoder::Deflate(DeflateDecoder::new(response)) + } + else if encoding.contains(&Encoding::EncodingExt("br".to_owned())) { + Decoder::Brotli(Decompressor::new(response, 1024)) + } else { + Decoder::Plain(response) + } } else { - Decoder::Plain + Decoder::Plain(response) } - } else { - Decoder::Plain - } + }; + Ok(StreamedResponse { decoder: decoder }) } } -pub enum Decoder { - Gzip(Option>>), - Deflate(DeflateDecoder>), - Brotli(Decompressor>), - Plain, +enum Decoder { + Gzip(GzDecoder), + Deflate(DeflateDecoder), + Brotli(Decompressor), + Plain(HyperResponse) } -fn prepare_devtools_request( - request_id: String, - url: ServoUrl, - method: Method, - headers: HeaderMap, - body: Option>, - pipeline_id: PipelineId, - now: Tm, - connect_time: u64, - send_time: u64, - is_xhr: bool, -) -> ChromeToDevtoolsControlMsg { +fn prepare_devtools_request(request_id: String, + url: ServoUrl, + method: Method, + headers: Headers, + body: Option>, + pipeline_id: PipelineId, + now: Tm, + connect_time: u64, + send_time: u64, + is_xhr: bool) -> ChromeToDevtoolsControlMsg { let request = DevtoolsHttpRequest { url: url, method: method, @@ -319,183 +344,150 @@ fn prepare_devtools_request( ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event) } -fn send_request_to_devtools( - msg: ChromeToDevtoolsControlMsg, - devtools_chan: &Sender, -) { - devtools_chan - .send(DevtoolsControlMsg::FromChrome(msg)) - .unwrap(); +fn send_request_to_devtools(msg: ChromeToDevtoolsControlMsg, + devtools_chan: &Sender) { + devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)).unwrap(); } -fn send_response_to_devtools( - devtools_chan: &Sender, - request_id: String, - headers: Option, - status: Option<(u16, Vec)>, - pipeline_id: PipelineId, -) { - let response = DevtoolsHttpResponse { - headers: headers, - status: status, - body: None, - pipeline_id: pipeline_id, - }; +fn send_response_to_devtools(devtools_chan: &Sender, + request_id: String, + headers: Option, + status: Option<(u16, Vec)>, + pipeline_id: PipelineId) { + let response = DevtoolsHttpResponse { headers: headers, status: status, body: None, pipeline_id: pipeline_id }; let net_event_response = NetworkEvent::HttpResponse(response); let msg = ChromeToDevtoolsControlMsg::NetworkEvent(request_id, net_event_response); let _ = devtools_chan.send(DevtoolsControlMsg::FromChrome(msg)); } -fn auth_from_cache( - auth_cache: &RwLock, - origin: &ImmutableOrigin, -) -> Option> { - if let Some(ref auth_entry) = auth_cache - .read() - .unwrap() - .entries - .get(&origin.ascii_serialization()) - { - let user_name = &auth_entry.user_name; - let password = &auth_entry.password; - Some(Authorization::basic(user_name, password)) +fn auth_from_cache(auth_cache: &RwLock, origin: &ImmutableOrigin) -> Option { + if let Some(ref auth_entry) = auth_cache.read().unwrap().entries.get(&origin.ascii_serialization()) { + let user_name = auth_entry.user_name.clone(); + let password = Some(auth_entry.password.clone()); + Some(Basic { username: user_name, password: password }) } else { None } } -fn obtain_response( - client: &Client, - url: &ServoUrl, - method: &Method, - request_headers: &HeaderMap, - data: &Option>, - load_data_method: &Method, - pipeline_id: &Option, - iters: u32, - request_id: Option<&str>, - is_xhr: bool, -) -> Box< - dyn Future< - Item = ( - HyperResponse, - Option, - ), - Error = NetworkError, - >, -> { - let mut headers = request_headers.clone(); - - // Avoid automatically sending request body if a redirect has occurred. - // - // TODO - This is the wrong behaviour according to the RFC. However, I'm not - // sure how much "correctness" vs. real-world is important in this case. - // - // https://tools.ietf.org/html/rfc7231#section-6.4 - let is_redirected_request = iters != 1; - let request_body; - match data { - &Some(ref d) if !is_redirected_request => { - headers.typed_insert(ContentLength(d.len() as u64)); - request_body = d.clone(); - }, - _ => { - if *load_data_method != Method::GET && *load_data_method != Method::HEAD { - headers.typed_insert(ContentLength(0)) +fn obtain_response(connector: &Pool, + url: &ServoUrl, + method: &Method, + request_headers: &Headers, + data: &Option>, + load_data_method: &Method, + pipeline_id: &Option, + iters: u32, + request_id: Option<&str>, + is_xhr: bool) + -> Result<(HyperResponse, Option), NetworkError> { + let null_data = None; + + // loop trying connections in connection pool + // they may have grown stale (disconnected), in which case we'll get + // a ConnectionAborted error. this loop tries again with a new + // connection. + loop { + let mut headers = request_headers.clone(); + + // Avoid automatically sending request body if a redirect has occurred. + // + // TODO - This is the wrong behaviour according to the RFC. However, I'm not + // sure how much "correctness" vs. real-world is important in this case. + // + // https://tools.ietf.org/html/rfc7231#section-6.4 + let is_redirected_request = iters != 1; + let request_body; + match data { + &Some(ref d) if !is_redirected_request => { + headers.set(ContentLength(d.len() as u64)); + request_body = data; } - request_body = vec![]; - }, - } + _ => { + if *load_data_method != Method::Get && *load_data_method != Method::Head { + headers.set(ContentLength(0)) + } + request_body = &null_data; + } + } - if log_enabled!(log::Level::Info) { - info!("{} {}", method, url); - for header in headers.iter() { - info!(" - {:?}", header); + if log_enabled!(log::Level::Info) { + info!("{} {}", method, url); + for header in headers.iter() { + info!(" - {}", header); + } + info!("{:?}", data); } - info!("{:?}", data); - } - let connect_start = precise_time_ms(); - // https://url.spec.whatwg.org/#percent-encoded-bytes - let request = HyperRequest::builder() - .method(method) - .uri( - url.clone() - .into_url() - .as_ref() - .replace("|", "%7C") - .replace("{", "%7B") - .replace("}", "%7D"), - ) - .body(WrappedBody::new(request_body.clone().into())); - - let mut request = match request { - Ok(request) => request, - Err(e) => return Box::new(future::result(Err(NetworkError::from_http_error(&e)))), - }; - *request.headers_mut() = headers.clone(); - let connect_end = precise_time_ms(); - - let request_id = request_id.map(|v| v.to_owned()); - let pipeline_id = pipeline_id.clone(); - let closure_url = url.clone(); - let method = method.clone(); - let send_start = precise_time_ms(); - - Box::new( - client - .request(request) - .and_then(move |res| { - let send_end = precise_time_ms(); - - let msg = if let Some(request_id) = request_id { - if let Some(pipeline_id) = pipeline_id { - Some(prepare_devtools_request( - request_id, - closure_url, - method.clone(), - headers, - Some(request_body.clone()), - pipeline_id, - time::now(), - connect_end - connect_start, - send_end - send_start, - is_xhr, - )) - // TODO: ^This is not right, connect_start is taken before contructing the - // request and connect_end at the end of it. send_start is takend before the - // connection too. I'm not sure it's currently possible to get the time at the - // point between the connection and the start of a request. - } else { - debug!("Not notifying devtools (no pipeline_id)"); - None - } - } else { - debug!("Not notifying devtools (no request_id)"); - None - }; - let decoder = Decoder::from_http_response(&res); - Ok(( - res.map(move |r| WrappedBody::new_with_decoder(r, decoder)), - msg, - )) - }) - .map_err(move |e| NetworkError::from_hyper_error(&e)), - ) + let connect_start = precise_time_ms(); + + let request = HyperRequest::with_connector(method.clone(), + url.clone().into_url(), + &*connector); + let mut request = match request { + Ok(request) => request, + Err(e) => return Err(NetworkError::from_hyper_error(&url, e)), + }; + *request.headers_mut() = headers.clone(); + + let connect_end = precise_time_ms(); + + let send_start = precise_time_ms(); + + let mut request_writer = match request.start() { + Ok(streaming) => streaming, + Err(e) => return Err(NetworkError::Internal(e.description().to_owned())), + }; + + if let Some(ref data) = *request_body { + if let Err(e) = request_writer.write_all(&data) { + return Err(NetworkError::Internal(e.description().to_owned())) + } + } + + let response = match request_writer.send() { + Ok(w) => w, + Err(HttpError::Io(ref io_error)) + if io_error.kind() == io::ErrorKind::ConnectionAborted || + io_error.kind() == io::ErrorKind::ConnectionReset => { + debug!("connection aborted ({:?}), possibly stale, trying new connection", io_error.description()); + continue; + }, + Err(e) => return Err(NetworkError::Internal(e.description().to_owned())), + }; + + let send_end = precise_time_ms(); + + let msg = if let Some(request_id) = request_id { + if let Some(pipeline_id) = *pipeline_id { + Some(prepare_devtools_request( + request_id.into(), + url.clone(), method.clone(), headers, + request_body.clone(), pipeline_id, time::now(), + connect_end - connect_start, send_end - send_start, is_xhr)) + } else { + debug!("Not notifying devtools (no pipeline_id)"); + None + } + } else { + debug!("Not notifying devtools (no request_id)"); + None + }; + return Ok((response, msg)); + } } /// [HTTP fetch](https://fetch.spec.whatwg.org#http-fetch) -pub fn http_fetch( - request: &mut Request, - cache: &mut CorsCache, - cors_flag: bool, - cors_preflight_flag: bool, - authentication_fetch_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +pub fn http_fetch(request: &mut Request, + cache: &mut CorsCache, + cors_flag: bool, + cors_preflight_flag: bool, + authentication_fetch_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { // This is a new async fetch, reset the channel we are waiting on *done_chan = None; // Step 1 @@ -528,12 +520,12 @@ pub fn http_fetch( // nothing to do, since actual_response is a function on response // Subsubstep 3 - if (res.response_type == ResponseType::Opaque && request.mode != RequestMode::NoCors) || - (res.response_type == ResponseType::OpaqueRedirect && - request.redirect_mode != RedirectMode::Manual) || - (res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) || - res.is_network_error() - { + if (res.response_type == ResponseType::Opaque && + request.mode != RequestMode::NoCors) || + (res.response_type == ResponseType::OpaqueRedirect && + request.redirect_mode != RedirectMode::Manual) || + (res.url_list.len() > 1 && request.redirect_mode != RedirectMode::Follow) || + res.is_network_error() { return Response::network_error(NetworkError::Internal("Request failed".into())); } @@ -546,14 +538,14 @@ pub fn http_fetch( if response.is_none() { // Substep 1 if cors_preflight_flag { - let method_cache_match = cache.match_method(&*request, request.method.clone()); + let method_cache_match = cache.match_method(&*request, + request.method.clone()); - let method_mismatch = !method_cache_match && - (!is_cors_safelisted_method(&request.method) || request.use_cors_preflight); - let header_mismatch = request.headers.iter().any(|(name, value)| { - !cache.match_header(&*request, &name) && - !is_cors_safelisted_request_header(&name, &value) - }); + let method_mismatch = !method_cache_match && (!is_cors_safelisted_method(&request.method) || + request.use_cors_preflight); + let header_mismatch = request.headers.iter().any(|view| + !cache.match_header(&*request, view.name()) && !is_cors_safelisted_request_header(&view) + ); // Sub-substep 1 if method_mismatch || header_mismatch { @@ -572,12 +564,7 @@ pub fn http_fetch( // Substep 3 let mut fetch_result = http_network_or_cache_fetch( - request, - authentication_fetch_flag, - cors_flag, - done_chan, - context, - ); + request, authentication_fetch_flag, cors_flag, done_chan, context); // Substep 4 if cors_flag && cors_check(&request, &fetch_result).is_err() { @@ -592,52 +579,32 @@ pub fn http_fetch( let mut response = response.unwrap(); // Step 5 - if response - .actual_response() - .status - .as_ref() - .map_or(false, is_redirect_status) - { + if response.actual_response().status.map_or(false, is_redirect_status) { // Substep 1. - if response - .actual_response() - .status - .as_ref() - .map_or(true, |s| s.0 != StatusCode::SEE_OTHER) - { + if response.actual_response().status.map_or(true, |s| s != StatusCode::SeeOther) { // TODO: send RST_STREAM frame } // Substep 2-3. - let location = response - .actual_response() - .headers - .get(header::LOCATION) - .and_then(|v| { - HeaderValue::to_str(v) - .map(|l| { - ServoUrl::parse_with_base(response.actual_response().url(), &l) - .map_err(|err| err.description().into()) - }) - .ok() - }); + let location = response.actual_response().headers.get::().map( + |l| ServoUrl::parse_with_base(response.actual_response().url(), l) + .map_err(|err| err.description().into())); // Substep 4. response.actual_response_mut().location_url = location; // Substep 5. response = match request.redirect_mode { - RedirectMode::Error => { - Response::network_error(NetworkError::Internal("Redirect mode error".into())) + RedirectMode::Error => Response::network_error(NetworkError::Internal("Redirect mode error".into())), + RedirectMode::Manual => { + response.to_filtered(ResponseType::OpaqueRedirect) }, - RedirectMode::Manual => response.to_filtered(ResponseType::OpaqueRedirect), RedirectMode::Follow => { // set back to default response.return_internal = true; - http_redirect_fetch( - request, cache, response, cors_flag, target, done_chan, context, - ) - }, + http_redirect_fetch(request, cache, response, + cors_flag, target, done_chan, context) + } }; } // set back to default @@ -647,15 +614,14 @@ pub fn http_fetch( } /// [HTTP redirect fetch](https://fetch.spec.whatwg.org#http-redirect-fetch) -pub fn http_redirect_fetch( - request: &mut Request, - cache: &mut CorsCache, - response: Response, - cors_flag: bool, - target: Target, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +pub fn http_redirect_fetch(request: &mut Request, + cache: &mut CorsCache, + response: Response, + cors_flag: bool, + target: Target, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { // Step 1 assert!(response.return_internal); @@ -664,17 +630,12 @@ pub fn http_redirect_fetch( // Step 2 None => return response, // Step 3 - Some(Err(err)) => { - return Response::network_error(NetworkError::Internal( - "Location URL parse failure: ".to_owned() + &err, - )) - }, + Some(Err(err)) => + return Response::network_error( + NetworkError::Internal("Location URL parse failure: ".to_owned() + &err)), // Step 4 - Some(Ok(ref url)) if !matches!(url.scheme(), "http" | "https") => { - return Response::network_error(NetworkError::Internal( - "Location URL not an HTTP(S) scheme".into(), - )) - }, + Some(Ok(ref url)) if !matches!(url.scheme(), "http" | "https") => + return Response::network_error(NetworkError::Internal("Location URL not an HTTP(S) scheme".into())), Some(Ok(url)) => url, }; @@ -689,17 +650,12 @@ pub fn http_redirect_fetch( // Step 7 let same_origin = match request.origin { Origin::Origin(ref origin) => *origin == location_url.origin(), - Origin::Client => panic!( - "Request origin should not be client for {}", - request.current_url() - ), + Origin::Client => panic!("Request origin should not be client for {}", request.current_url()), }; let has_credentials = has_credentials(&location_url); if request.mode == RequestMode::CorsMode && !same_origin && has_credentials { - return Response::network_error(NetworkError::Internal( - "Cross-origin credentials check failed".into(), - )); + return Response::network_error(NetworkError::Internal("Cross-origin credentials check failed".into())); } // Step 8 @@ -708,13 +664,8 @@ pub fn http_redirect_fetch( } // Step 9 - if response - .actual_response() - .status - .as_ref() - .map_or(true, |s| s.0 != StatusCode::SEE_OTHER) && - request.body.as_ref().map_or(false, |b| b.is_empty()) - { + if response.actual_response().status.map_or(true, |s| s != StatusCode::SeeOther) && + request.body.as_ref().map_or(false, |b| b.is_empty()) { return Response::network_error(NetworkError::Internal("Request body is not done".into())); } @@ -724,16 +675,10 @@ pub fn http_redirect_fetch( } // Step 11 - if response - .actual_response() - .status - .as_ref() - .map_or(false, |(code, _)| { - ((*code == StatusCode::MOVED_PERMANENTLY || *code == StatusCode::FOUND) && - request.method == Method::POST) || - (*code == StatusCode::SEE_OTHER && request.method != Method::HEAD) - }) { - request.method = Method::GET; + if response.actual_response().status.map_or(false, |code| + ((code == StatusCode::MovedPermanently || code == StatusCode::Found) && request.method == Method::Post) || + (code == StatusCode::SeeOther && request.method != Method::Head)) { + request.method = Method::Get; request.body = None; } @@ -751,40 +696,32 @@ pub fn http_redirect_fetch( // Step 15 let recursive_flag = request.redirect_mode != RedirectMode::Manual; - main_fetch( - request, - cache, - cors_flag, - recursive_flag, - target, - done_chan, - context, - ) + main_fetch(request, cache, cors_flag, recursive_flag, target, done_chan, context) } fn try_immutable_origin_to_hyper_origin(url_origin: &ImmutableOrigin) -> Option { match *url_origin { - ImmutableOrigin::Opaque(_) => Some(HyperOrigin::NULL), - ImmutableOrigin::Tuple(ref scheme, ref host, ref port) => { - HyperOrigin::try_from_parts(&scheme, &host.to_string(), Some(port.clone())).ok() - }, + // TODO (servo/servo#15569) Set "Origin: null" when hyper supports it + ImmutableOrigin::Opaque(_) => None, + ImmutableOrigin::Tuple(ref scheme, ref host, ref port) => + Some(HyperOrigin::new(scheme.clone(), host.to_string(), Some(port.clone()))) } } /// [HTTP network or cache fetch](https://fetch.spec.whatwg.org#http-network-or-cache-fetch) -fn http_network_or_cache_fetch( - request: &mut Request, - authentication_fetch_flag: bool, - cors_flag: bool, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +fn http_network_or_cache_fetch(request: &mut Request, + authentication_fetch_flag: bool, + cors_flag: bool, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { // TODO: Implement Window enum for Request let request_has_no_window = true; // Step 2 let mut http_request; - let http_request = if request_has_no_window && request.redirect_mode == RedirectMode::Error { + let http_request = if request_has_no_window && + request.redirect_mode == RedirectMode::Error { request } else { // Step 3 @@ -796,65 +733,58 @@ fn http_network_or_cache_fetch( // Step 4 let credentials_flag = match http_request.credentials_mode { CredentialsMode::Include => true, - CredentialsMode::CredentialsSameOrigin - if http_request.response_tainting == ResponseTainting::Basic => - { - true - }, - _ => false, + CredentialsMode::CredentialsSameOrigin if http_request.response_tainting == ResponseTainting::Basic + => true, + _ => false }; let content_length_value = match http_request.body { - None => match http_request.method { - // Step 6 - Method::POST | Method::PUT => Some(0), - // Step 5 - _ => None, - }, + None => + match http_request.method { + // Step 6 + Method::Post | Method::Put => + Some(0), + // Step 5 + _ => None + }, // Step 7 - Some(ref http_request_body) => Some(http_request_body.len() as u64), + Some(ref http_request_body) => Some(http_request_body.len() as u64) }; // Step 8 if let Some(content_length_value) = content_length_value { - http_request - .headers - .typed_insert(ContentLength(content_length_value)); + http_request.headers.set(ContentLength(content_length_value)); if http_request.keep_alive { // Step 9 TODO: needs request's client object } } + // Step 10 match http_request.referrer { Referrer::NoReferrer => (), - Referrer::ReferrerUrl(ref http_request_referrer) => http_request - .headers - .typed_insert::(http_request_referrer.to_string().parse().unwrap()), + Referrer::ReferrerUrl(ref http_request_referrer) => + http_request.headers.set(Referer(http_request_referrer.to_string())), Referrer::Client => - // it should be impossible for referrer to be anything else during fetching - // https://fetch.spec.whatwg.org/#concept-request-referrer - { + // it should be impossible for referrer to be anything else during fetching + // https://fetch.spec.whatwg.org/#concept-request-referrer unreachable!() - }, }; // Step 11 - if cors_flag || (http_request.method != Method::GET && http_request.method != Method::HEAD) { + if cors_flag || (http_request.method != Method::Get && http_request.method != Method::Head) { debug_assert_ne!(http_request.origin, Origin::Client); if let Origin::Origin(ref url_origin) = http_request.origin { if let Some(hyper_origin) = try_immutable_origin_to_hyper_origin(url_origin) { - http_request.headers.typed_insert(hyper_origin) + http_request.headers.set(hyper_origin) } } } // Step 12 - if !http_request.headers.contains_key(header::USER_AGENT) { + if !http_request.headers.has::() { let user_agent = context.user_agent.clone().into_owned(); - http_request - .headers - .typed_insert::(user_agent.parse().unwrap()); + http_request.headers.set(UserAgent(user_agent)); } match http_request.cache_mode { @@ -864,46 +794,33 @@ fn http_network_or_cache_fetch( }, // Step 14 - CacheMode::NoCache if !http_request.headers.contains_key(header::CACHE_CONTROL) => { - http_request - .headers - .typed_insert(CacheControl::new().with_max_age(Duration::from_secs(0))); + CacheMode::NoCache if !http_request.headers.has::() => { + http_request.headers.set(CacheControl(vec![CacheDirective::MaxAge(0)])); }, // Step 15 CacheMode::Reload | CacheMode::NoStore => { // Substep 1 - if !http_request.headers.contains_key(header::PRAGMA) { - http_request.headers.typed_insert(Pragma::no_cache()); + if !http_request.headers.has::() { + http_request.headers.set(Pragma::NoCache); } // Substep 2 - if !http_request.headers.contains_key(header::CACHE_CONTROL) { - http_request - .headers - .typed_insert(CacheControl::new().with_no_cache()); + if !http_request.headers.has::() { + http_request.headers.set(CacheControl(vec![CacheDirective::NoCache])); } }, - _ => {}, + _ => {} } // Step 16 let current_url = http_request.current_url(); - let host = Host::from( - format!( - "{}{}", - current_url.host_str().unwrap(), - current_url - .port() - .map(|v| format!(":{}", v)) - .unwrap_or("".into()) - ) - .parse::() - .unwrap(), - ); - - http_request.headers.typed_insert(host); + let host = Host { + hostname: current_url.host_str().unwrap().to_owned(), + port: current_url.port() + }; + http_request.headers.set(host); // unlike http_loader, we should not set the accept header // here, according to the fetch spec set_default_accept_encoding(&mut http_request.headers); @@ -914,13 +831,11 @@ fn http_network_or_cache_fetch( // Substep 1 // TODO http://mxr.mozilla.org/servo/source/components/net/http_loader.rs#504 // XXXManishearth http_loader has block_cookies: support content blocking here too - set_request_cookies( - ¤t_url, - &mut http_request.headers, - &context.state.cookie_jar, - ); + set_request_cookies(¤t_url, + &mut http_request.headers, + &context.state.cookie_jar); // Substep 2 - if !http_request.headers.contains_key(header::AUTHORIZATION) { + if !http_request.headers.has::>() { // Substep 3 let mut authorization_value = None; @@ -934,16 +849,16 @@ fn http_network_or_cache_fetch( // Substep 5 if authentication_fetch_flag && authorization_value.is_none() { if has_credentials(¤t_url) { - authorization_value = Some(Authorization::basic( - current_url.username(), - current_url.password().unwrap_or(""), - )); + authorization_value = Some(Basic { + username: current_url.username().to_owned(), + password: current_url.password().map(str::to_owned) + }) } } // Substep 6 if let Some(basic) = authorization_value { - http_request.headers.typed_insert(basic); + http_request.headers.set(Authorization(basic)); } } } @@ -962,33 +877,26 @@ fn http_network_or_cache_fetch( if let Some(response_from_cache) = http_cache.construct_response(&http_request, done_chan) { let response_headers = response_from_cache.response.headers.clone(); // Substep 1, 2, 3, 4 - let (cached_response, needs_revalidation) = - match (http_request.cache_mode, &http_request.mode) { - (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false), - (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => { - (Some(response_from_cache.response), false) - }, - (CacheMode::OnlyIfCached, _) | - (CacheMode::NoStore, _) | - (CacheMode::Reload, _) => (None, false), - (_, _) => ( - Some(response_from_cache.response), - response_from_cache.needs_validation, - ), - }; + let (cached_response, needs_revalidation) = match (http_request.cache_mode, &http_request.mode) { + (CacheMode::ForceCache, _) => (Some(response_from_cache.response), false), + (CacheMode::OnlyIfCached, &RequestMode::SameOrigin) => (Some(response_from_cache.response), false), + (CacheMode::OnlyIfCached, _) | (CacheMode::NoStore, _) | (CacheMode::Reload, _) => (None, false), + (_, _) => (Some(response_from_cache.response), response_from_cache.needs_validation) + }; if needs_revalidation { revalidating_flag = true; // Substep 5 - if let Some(http_date) = response_headers.typed_get::() { - let http_date: SystemTime = http_date.into(); - http_request - .headers - .typed_insert(IfModifiedSince::from(http_date)); + // TODO: find out why the typed header getter return None from the headers of cached responses. + if let Some(date_slice) = response_headers.get_raw("Last-Modified") { + let date_string = String::from_utf8_lossy(&date_slice[0]); + if let Ok(http_date) = HttpDate::from_str(&date_string) { + http_request.headers.set(IfModifiedSince(http_date)); + } } - if let Some(entity_tag) = response_headers.get(header::ETAG) { - http_request - .headers - .insert(header::IF_NONE_MATCH, entity_tag.clone()); + if let Some(entity_tag) = + response_headers.get_raw("ETag") { + http_request.headers.set_raw("If-None-Match", entity_tag.to_vec()); + } } else { // Substep 6 @@ -1003,11 +911,8 @@ fn http_network_or_cache_fetch( // We wait for the response in the cache to "finish", // with a body of either Done or Cancelled. loop { - match ch - .1 - .recv() - .expect("HTTP cache should always send Done or Cancelled") - { + match ch.1.recv() + .expect("HTTP cache should always send Done or Cancelled") { Data::Payload(_) => {}, Data::Done => break, // Return the full response as if it was initially cached as such. Data::Cancelled => { @@ -1015,7 +920,7 @@ fn http_network_or_cache_fetch( // Set response to None, which will trigger a network fetch below. *response = None; break; - }, + } } } } @@ -1029,30 +934,25 @@ fn http_network_or_cache_fetch( if response.is_none() { // Substep 1 if http_request.cache_mode == CacheMode::OnlyIfCached { - return Response::network_error(NetworkError::Internal( - "Couldn't find response in cache".into(), - )); + return Response::network_error( + NetworkError::Internal("Couldn't find response in cache".into())) } } // More Step 22 if response.is_none() { // Substep 2 - let forward_response = - http_network_fetch(http_request, credentials_flag, done_chan, context); + let forward_response = http_network_fetch(http_request, credentials_flag, + done_chan, context); // Substep 3 if let Some((200...399, _)) = forward_response.raw_status { - if !http_request.method.is_safe() { + if !http_request.method.safe() { if let Ok(mut http_cache) = context.state.http_cache.write() { http_cache.invalidate(&http_request, &forward_response); } } } // Substep 4 - if revalidating_flag && forward_response - .status - .as_ref() - .map_or(false, |s| s.0 == StatusCode::NOT_MODIFIED) - { + if revalidating_flag && forward_response.status.map_or(false, |s| s == StatusCode::NotModified) { if let Ok(mut http_cache) = context.state.http_cache.write() { response = http_cache.refresh(&http_request, forward_response.clone(), done_chan); wait_for_cached_response(done_chan, &mut response); @@ -1076,9 +976,7 @@ fn http_network_or_cache_fetch( // Step 23 // FIXME: Figure out what to do with request window objects - if let (Some((StatusCode::UNAUTHORIZED, _)), false, true) = - (response.status.as_ref(), cors_flag, credentials_flag) - { + if let (Some(StatusCode::Unauthorized), false, true) = (response.status, cors_flag, credentials_flag) { // Substep 1 // TODO: Spec says requires testing on multiple WWW-Authenticate headers @@ -1098,22 +996,16 @@ fn http_network_or_cache_fetch( } // Substep 4 - response = http_network_or_cache_fetch( - http_request, - true, /* authentication flag */ - cors_flag, - done_chan, - context, - ); + response = http_network_or_cache_fetch(http_request, + true /* authentication flag */, + cors_flag, done_chan, context); } // Step 24 - if let Some((StatusCode::PROXY_AUTHENTICATION_REQUIRED, _)) = response.status.as_ref() { + if let Some(StatusCode::ProxyAuthenticationRequired) = response.status { // Step 1 if request_has_no_window { - return Response::network_error(NetworkError::Internal( - "Can't find Window object".into(), - )); + return Response::network_error(NetworkError::Internal("Can't find Window object".into())); } // Step 2 @@ -1142,12 +1034,11 @@ fn http_network_or_cache_fetch( } /// [HTTP network fetch](https://fetch.spec.whatwg.org/#http-network-fetch) -fn http_network_fetch( - request: &Request, - credentials_flag: bool, - done_chan: &mut DoneChannel, - context: &FetchContext, -) -> Response { +fn http_network_fetch(request: &Request, + credentials_flag: bool, + done_chan: &mut DoneChannel, + context: &FetchContext) + -> Response { // Step 1 // nothing to do here, since credentials_flag is already a boolean @@ -1163,130 +1054,121 @@ fn http_network_fetch( // Step 5 let url = request.current_url(); - let request_id = context - .devtools_chan - .as_ref() - .map(|_| uuid::Uuid::new_v4().simple().to_string()); + let request_id = context.devtools_chan.as_ref().map(|_| { + uuid::Uuid::new_v4().simple().to_string() + }); // XHR uses the default destination; other kinds of fetches (which haven't been implemented yet) // do not. Once we support other kinds of fetches we'll need to be more fine grained here // since things like image fetches are classified differently by devtools let is_xhr = request.destination == Destination::None; - let response_future = obtain_response( - &context.state.client, - &url, - &request.method, - &request.headers, - &request.body, - &request.method, - &request.pipeline_id, - request.redirect_count + 1, - request_id.as_ref().map(Deref::deref), - is_xhr, - ); + let wrapped_response = obtain_response(&context.state.connector, + &url, + &request.method, + &request.headers, + &request.body, &request.method, + &request.pipeline_id, request.redirect_count + 1, + request_id.as_ref().map(Deref::deref), is_xhr); let pipeline_id = request.pipeline_id; - // This will only get the headers, the body is read later - let (res, msg) = match response_future.wait() { + let (res, msg) = match wrapped_response { Ok(wrapped_response) => wrapped_response, Err(error) => return Response::network_error(error), }; if log_enabled!(log::Level::Info) { info!("response for {}", url); - for header in res.headers().iter() { - info!(" - {:?}", header); + for header in res.headers.iter() { + info!(" - {}", header); } } let mut response = Response::new(url.clone()); - response.status = Some(( - res.status(), - res.status().canonical_reason().unwrap_or("").into(), - )); - response.raw_status = Some(( - res.status().as_u16(), - res.status().canonical_reason().unwrap_or("").into(), - )); - response.headers = res.headers().clone(); + response.status = Some(res.status); + response.raw_status = Some((res.status_raw().0, + res.status_raw().1.as_bytes().to_vec())); + response.headers = res.headers.clone(); response.referrer = request.referrer.to_url().cloned(); response.referrer_policy = request.referrer_policy.clone(); let res_body = response.body.clone(); - // We're about to spawn a future to be waited on here + // We're about to spawn a thread to be waited on here let (done_sender, done_receiver) = channel(); *done_chan = Some((done_sender.clone(), done_receiver)); - let meta = match response - .metadata() - .expect("Response metadata should exist at this stage") - { + let meta = match response.metadata().expect("Response metadata should exist at this stage") { FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_ }; let devtools_sender = context.devtools_chan.clone(); let meta_status = meta.status.clone(); let meta_headers = meta.headers.clone(); let cancellation_listener = context.cancellation_listener.clone(); if cancellation_listener.lock().unwrap().cancelled() { - return Response::network_error(NetworkError::Internal("Fetch aborted".into())); + return Response::network_error(NetworkError::Internal("Fetch aborted".into())) } + thread::Builder::new().name(format!("fetch worker thread")).spawn(move || { + match StreamedResponse::from_http_response(res) { + Ok(mut res) => { + *res_body.lock().unwrap() = ResponseBody::Receiving(vec![]); + + if let Some(ref sender) = devtools_sender { + if let Some(m) = msg { + send_request_to_devtools(m, &sender); + } - *res_body.lock().unwrap() = ResponseBody::Receiving(vec![]); + // --- Tell devtools that we got a response + // Send an HttpResponse message to devtools with the corresponding request_id + if let Some(pipeline_id) = pipeline_id { + send_response_to_devtools( + &sender, request_id.unwrap(), + meta_headers.map(Serde::into_inner), + meta_status, + pipeline_id); + } + } - if let Some(ref sender) = devtools_sender { - if let Some(m) = msg { - send_request_to_devtools(m, &sender); + loop { + if cancellation_listener.lock().unwrap().cancelled() { + *res_body.lock().unwrap() = ResponseBody::Done(vec![]); + let _ = done_sender.send(Data::Cancelled); + return; + } + match read_block(&mut res) { + Ok(Data::Payload(chunk)) => { + if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { + body.extend_from_slice(&chunk); + let _ = done_sender.send(Data::Payload(chunk)); + } + }, + Ok(Data::Done) | Err(_) => { + let mut body = res_body.lock().unwrap(); + let completed_body = match *body { + ResponseBody::Receiving(ref mut body) => { + mem::replace(body, vec![]) + }, + _ => vec![], + }; + *body = ResponseBody::Done(completed_body); + let _ = done_sender.send(Data::Done); + break; + } + Ok(Data::Cancelled) => unreachable!() // read_block doesn't return Data::Cancelled + } + } + } + Err(_) => { + // XXXManishearth we should propagate this error somehow + *res_body.lock().unwrap() = ResponseBody::Done(vec![]); + let _ = done_sender.send(Data::Done); + } } + }).expect("Thread spawning failed"); - // --- Tell devtools that we got a response - // Send an HttpResponse message to devtools with the corresponding request_id - if let Some(pipeline_id) = pipeline_id { - send_response_to_devtools( - &sender, - request_id.unwrap(), - meta_headers.map(Serde::into_inner), - meta_status, - pipeline_id, - ); - } - } + // TODO these substeps aren't possible yet + // Substep 1 - let done_sender = done_sender.clone(); - let done_sender2 = done_sender.clone(); - HANDLE.lock().unwrap().spawn( - res.into_body() - .map_err(|_| ()) - .fold(res_body, move |res_body, chunk| { - if cancellation_listener.lock().unwrap().cancelled() { - *res_body.lock().unwrap() = ResponseBody::Done(vec![]); - let _ = done_sender.send(Data::Cancelled); - return future::failed(()); - } - if let ResponseBody::Receiving(ref mut body) = *res_body.lock().unwrap() { - let bytes = chunk.into_bytes(); - body.extend_from_slice(&*bytes); - let _ = done_sender.send(Data::Payload(bytes.to_vec())); - } - future::ok(res_body) - }) - .and_then(move |res_body| { - let mut body = res_body.lock().unwrap(); - let completed_body = match *body { - ResponseBody::Receiving(ref mut body) => mem::replace(body, vec![]), - _ => vec![], - }; - *body = ResponseBody::Done(completed_body); - let _ = done_sender2.send(Data::Done); - future::ok(()) - }) - .map_err(|_| ()), - ); - - // TODO these substeps aren't possible yet - // Substep 1 - - // Substep 2 + // Substep 2 // TODO Determine if response was retrieved over HTTPS // TODO Servo needs to decide what ciphers are to be treated as "deprecated" @@ -1301,9 +1183,11 @@ fn http_network_fetch( // TODO when https://bugzilla.mozilla.org/show_bug.cgi?id=1030660 // is resolved, this step will become uneccesary // TODO this step - if let Some(encoding) = response.headers.typed_get::() { - if encoding.contains("gzip") { - } else if encoding.contains("compress") { + if let Some(encoding) = response.headers.get::() { + if encoding.contains(&Encoding::Gzip) { + } + + else if encoding.contains(&Encoding::Compress) { } }; @@ -1325,31 +1209,26 @@ fn http_network_fetch( // TODO these steps // Step 16 - // Substep 1 - // Substep 2 - // Sub-substep 1 - // Sub-substep 2 - // Sub-substep 3 - // Sub-substep 4 - // Substep 3 + // Substep 1 + // Substep 2 + // Sub-substep 1 + // Sub-substep 2 + // Sub-substep 3 + // Sub-substep 4 + // Substep 3 // Step 16 response } /// [CORS preflight fetch](https://fetch.spec.whatwg.org#cors-preflight-fetch) -fn cors_preflight_fetch( - request: &Request, - cache: &mut CorsCache, - context: &FetchContext, -) -> Response { +fn cors_preflight_fetch(request: &Request, + cache: &mut CorsCache, + context: &FetchContext) + -> Response { // Step 1 - let mut preflight = Request::new( - request.current_url(), - Some(request.origin.clone()), - request.pipeline_id, - ); - preflight.method = Method::OPTIONS; + let mut preflight = Request::new(request.current_url(), Some(request.origin.clone()), request.pipeline_id); + preflight.method = Method::Options; preflight.initiator = request.initiator.clone(); preflight.destination = request.destination.clone(); preflight.origin = request.origin.clone(); @@ -1357,72 +1236,45 @@ fn cors_preflight_fetch( preflight.referrer_policy = request.referrer_policy; // Step 2 - preflight - .headers - .typed_insert::(AccessControlRequestMethod::from( - request.method.clone(), - )); + preflight.headers.set::( + AccessControlRequestMethod(request.method.clone())); // Step 3 - let mut headers = request - .headers + let mut headers = request.headers .iter() - .filter(|(name, value)| !is_cors_safelisted_request_header(&name, &value)) - .map(|(name, _)| name.as_str()) - .collect::>(); + .filter(|view| !is_cors_safelisted_request_header(view)) + .map(|view| UniCase(view.name().to_ascii_lowercase().to_owned())) + .collect::>>(); headers.sort(); - let headers = headers - .iter() - .map(|name| HeaderName::from_str(name).unwrap()) - .collect::>(); // Step 4 if !headers.is_empty() { - preflight - .headers - .typed_insert(AccessControlRequestHeaders::from_iter(headers)); + preflight.headers.set::(AccessControlRequestHeaders(headers)); } // Step 5 let response = http_network_or_cache_fetch(&mut preflight, false, false, &mut None, context); // Step 6 - if cors_check(&request, &response).is_ok() && response - .status - .as_ref() - .map_or(false, |(status, _)| status.is_success()) - { + if cors_check(&request, &response).is_ok() && + response.status.map_or(false, |status| status.is_success()) { // Substep 1, 2 - let mut methods = if response - .headers - .contains_key(header::ACCESS_CONTROL_ALLOW_METHODS) - { - match response.headers.typed_get::() { - Some(methods) => methods.iter().collect(), + let mut methods = if response.headers.has::() { + match response.headers.get::() { + Some(&AccessControlAllowMethods(ref m)) => m.clone(), // Substep 4 - None => { - return Response::network_error(NetworkError::Internal( - "CORS ACAM check failed".into(), - )) - }, + None => return Response::network_error(NetworkError::Internal("CORS ACAM check failed".into())) } } else { vec![] }; // Substep 3 - let header_names = if response - .headers - .contains_key(header::ACCESS_CONTROL_ALLOW_HEADERS) - { - match response.headers.typed_get::() { - Some(names) => names.iter().collect(), + let header_names = if response.headers.has::() { + match response.headers.get::() { + Some(&AccessControlAllowHeaders(ref hn)) => hn.clone(), // Substep 4 - None => { - return Response::network_error(NetworkError::Internal( - "CORS ACAH check failed".into(), - )) - }, + None => return Response::network_error(NetworkError::Internal("CORS ACAH check failed".into())) } } else { vec![] @@ -1430,12 +1282,10 @@ fn cors_preflight_fetch( // Substep 5 if (methods.iter().any(|m| m.as_ref() == "*") || - header_names.iter().any(|hn| hn.as_str() == "*")) && - request.credentials_mode == CredentialsMode::Include - { - return Response::network_error(NetworkError::Internal( - "CORS ACAH/ACAM and request credentials mode mismatch".into(), - )); + header_names.iter().any(|hn| &**hn == "*")) && + request.credentials_mode == CredentialsMode::Include { + return Response::network_error( + NetworkError::Internal("CORS ACAH/ACAM and request credentials mode mismatch".into())); } // Substep 6 @@ -1444,49 +1294,32 @@ fn cors_preflight_fetch( } // Substep 7 - debug!( - "CORS check: Allowed methods: {:?}, current method: {:?}", - methods, request.method - ); + debug!("CORS check: Allowed methods: {:?}, current method: {:?}", + methods, request.method); if methods.iter().all(|method| *method != request.method) && !is_cors_safelisted_method(&request.method) && - methods.iter().all(|m| m.as_ref() != "*") - { - return Response::network_error(NetworkError::Internal( - "CORS method check failed".into(), - )); + methods.iter().all(|m| m.as_ref() != "*") { + return Response::network_error(NetworkError::Internal("CORS method check failed".into())); } // Substep 8 - if request.headers.iter().any(|(name, _)| { - name == header::AUTHORIZATION && header_names.iter().all(|hn| hn != name) - }) { - return Response::network_error(NetworkError::Internal( - "CORS authorization check failed".into(), - )); + if request.headers.iter().any( + |header| header.name() == "authorization" && + header_names.iter().all(|hn| *hn != UniCase(header.name()))) { + return Response::network_error(NetworkError::Internal("CORS authorization check failed".into())); } // Substep 9 - debug!( - "CORS check: Allowed headers: {:?}, current headers: {:?}", - header_names, request.headers - ); - let set: HashSet<&HeaderName> = HashSet::from_iter(header_names.iter()); - if request.headers.iter().any(|(name, value)| { - !set.contains(name) && !is_cors_safelisted_request_header(&name, &value) - }) { - return Response::network_error(NetworkError::Internal( - "CORS headers check failed".into(), - )); + debug!("CORS check: Allowed headers: {:?}, current headers: {:?}", header_names, request.headers); + let set: HashSet<&UniCase> = HashSet::from_iter(header_names.iter()); + if request.headers.iter().any( + |ref hv| !set.contains(&UniCase(hv.name().to_owned())) && !is_cors_safelisted_request_header(hv)) { + return Response::network_error(NetworkError::Internal("CORS headers check failed".into())); } // Substep 10, 11 - let max_age: Duration = response - .headers - .typed_get::() - .map(|acma| acma.into()) - .unwrap_or(Duration::from_secs(0)); - let max_age = max_age.as_secs() as u32; + let max_age = response.headers.get::().map(|acma| acma.0).unwrap_or(0); + // Substep 12 // TODO: Need to define what an imposed limit on max-age is @@ -1513,28 +1346,27 @@ fn cors_preflight_fetch( /// [CORS check](https://fetch.spec.whatwg.org#concept-cors-check) fn cors_check(request: &Request, response: &Response) -> Result<(), ()> { // Step 1 - let origin = response.headers.typed_get::(); + let origin = response.headers.get::().cloned(); // Step 2 let origin = origin.ok_or(())?; // Step 3 if request.credentials_mode != CredentialsMode::Include && - origin == AccessControlAllowOrigin::ANY - { + origin == AccessControlAllowOrigin::Any { return Ok(()); } // Step 4 - let origin = match origin.origin() { - Some(origin) => origin, + let origin = match origin { + AccessControlAllowOrigin::Value(origin) => origin, // if it's Any or Null at this point, there's nothing to do but return Err(()) - None => return Err(()), + _ => return Err(()) }; match request.origin { - Origin::Origin(ref o) if o.ascii_serialization() == origin.to_string().trim() => {}, - _ => return Err(()), + Origin::Origin(ref o) if o.ascii_serialization() == origin.trim() => {}, + _ => return Err(()) } // Step 5 @@ -1543,9 +1375,7 @@ fn cors_check(request: &Request, response: &Response) -> Result<(), ()> { } // Step 6 - let credentials = response - .headers - .typed_get::(); + let credentials = response.headers.get::().cloned(); // Step 7 if credentials.is_some() { @@ -1560,22 +1390,20 @@ fn has_credentials(url: &ServoUrl) -> bool { !url.username().is_empty() || url.password().is_some() } -fn is_no_store_cache(headers: &HeaderMap) -> bool { - headers.contains_key(header::IF_MODIFIED_SINCE) | - headers.contains_key(header::IF_NONE_MATCH) | - headers.contains_key(header::IF_UNMODIFIED_SINCE) | - headers.contains_key(header::IF_MATCH) | - headers.contains_key(header::IF_RANGE) +fn is_no_store_cache(headers: &Headers) -> bool { + headers.has::() | headers.has::() | + headers.has::() | headers.has::() | + headers.has::() } /// -pub fn is_redirect_status(status: &(StatusCode, String)) -> bool { - match status.0 { - StatusCode::MOVED_PERMANENTLY | - StatusCode::FOUND | - StatusCode::SEE_OTHER | - StatusCode::TEMPORARY_REDIRECT | - StatusCode::PERMANENT_REDIRECT => true, +pub fn is_redirect_status(status: StatusCode) -> bool { + match status { + StatusCode::MovedPermanently | + StatusCode::Found | + StatusCode::SeeOther | + StatusCode::TemporaryRedirect | + StatusCode::PermanentRedirect => true, _ => false, } } diff --git a/components/net/image_cache.rs b/components/net/image_cache.rs index cf95d3fc1fdf..40ef8041ef79 100644 --- a/components/net/image_cache.rs +++ b/components/net/image_cache.rs @@ -4,18 +4,19 @@ use embedder_traits::resources::{self, Resource}; use immeta::load_from_buf; -use net_traits::image::base::{load_from_memory, Image, ImageMetadata, PixelFormat}; +use net_traits::{FetchMetadata, FetchResponseMsg, NetworkError}; +use net_traits::image::base::{Image, ImageMetadata, PixelFormat, load_from_memory}; use net_traits::image_cache::{CanRequestImages, ImageCache, ImageResponder}; use net_traits::image_cache::{ImageOrMetadataAvailable, ImageResponse, ImageState}; use net_traits::image_cache::{PendingImageId, UsePlaceholder}; -use net_traits::{FetchMetadata, FetchResponseMsg, NetworkError}; use servo_url::ServoUrl; -use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::io; use std::mem; use std::sync::{Arc, Mutex}; use std::thread; +use webrender_api; /// /// TODO(gw): Remaining work on image cache: @@ -35,39 +36,39 @@ fn decode_bytes_sync(key: LoadKey, bytes: &[u8]) -> DecoderMsg { let image = load_from_memory(bytes); DecoderMsg { key: key, - image: image, + image: image } } -fn get_placeholder_image( - webrender_api: &webrender_api::RenderApi, - data: &[u8], -) -> io::Result> { +fn get_placeholder_image(webrender_api: &webrender_api::RenderApi, data: &[u8]) -> io::Result> { let mut image = load_from_memory(&data).unwrap(); set_webrender_image_key(webrender_api, &mut image); Ok(Arc::new(image)) } fn set_webrender_image_key(webrender_api: &webrender_api::RenderApi, image: &mut Image) { - if image.id.is_some() { - return; - } + if image.id.is_some() { return; } let mut bytes = Vec::new(); let is_opaque = match image.format { PixelFormat::BGRA8 => { bytes.extend_from_slice(&*image.bytes); - pixels::premultiply_inplace(bytes.as_mut_slice()) - }, + premultiply(bytes.as_mut_slice()) + } PixelFormat::RGB8 => { for bgr in image.bytes.chunks(3) { - bytes.extend_from_slice(&[bgr[2], bgr[1], bgr[0], 0xff]); + bytes.extend_from_slice(&[ + bgr[2], + bgr[1], + bgr[0], + 0xff + ]); } true - }, + } PixelFormat::K8 | PixelFormat::KA8 => { panic!("Not support by webrender yet"); - }, + } }; let descriptor = webrender_api::ImageDescriptor { size: webrender_api::DeviceUintSize::new(image.width, image.height), @@ -85,6 +86,30 @@ fn set_webrender_image_key(webrender_api: &webrender_api::RenderApi, image: &mut image.id = Some(image_key); } +// Returns true if the image was found to be +// completely opaque. +fn premultiply(data: &mut [u8]) -> bool { + let mut is_opaque = true; + let length = data.len(); + + let mut i = 0; + while i < length { + let b = data[i + 0] as u32; + let g = data[i + 1] as u32; + let r = data[i + 2] as u32; + let a = data[i + 3] as u32; + + data[i + 0] = (b * a / 255) as u8; + data[i + 1] = (g * a / 255) as u8; + data[i + 2] = (r * a / 255) as u8; + + i += 4; + is_opaque = is_opaque && a == 255; + } + + is_opaque +} + // ====================================================================== // Aux structs and enums. // ====================================================================== @@ -119,22 +144,20 @@ impl AllPendingLoads { } fn remove(&mut self, key: &LoadKey) -> Option { - self.loads.remove(key).and_then(|pending_load| { - self.url_to_load_key.remove(&pending_load.url).unwrap(); - Some(pending_load) - }) + self.loads.remove(key). + and_then(|pending_load| { + self.url_to_load_key.remove(&pending_load.url).unwrap(); + Some(pending_load) + }) } - fn get_cached<'a>( - &'a mut self, - url: ServoUrl, - can_request: CanRequestImages, - ) -> CacheResult<'a> { + fn get_cached<'a>(&'a mut self, url: ServoUrl, can_request: CanRequestImages) + -> CacheResult<'a> { match self.url_to_load_key.entry(url.clone()) { Occupied(url_entry) => { let load_key = url_entry.get(); CacheResult::Hit(*load_key, self.loads.get_mut(load_key).unwrap()) - }, + } Vacant(url_entry) => { if can_request == CanRequestImages::No { return CacheResult::Miss(None); @@ -149,9 +172,9 @@ impl AllPendingLoads { Vacant(load_entry) => { let mut_load = load_entry.insert(pending_load); CacheResult::Miss(Some((load_key, mut_load))) - }, + } } - }, + } } } } @@ -226,12 +249,14 @@ impl ImageBytes { type LoadKey = PendingImageId; struct LoadKeyGenerator { - counter: u64, + counter: u64 } impl LoadKeyGenerator { fn new() -> LoadKeyGenerator { - LoadKeyGenerator { counter: 0 } + LoadKeyGenerator { + counter: 0 + } } fn next(&mut self) -> PendingImageId { self.counter += 1; @@ -242,7 +267,7 @@ impl LoadKeyGenerator { enum LoadResult { Loaded(Image), PlaceholderLoaded(Arc), - None, + None } /// Represents an image that is either being loaded @@ -269,10 +294,10 @@ struct PendingLoad { impl PendingLoad { fn new(url: ServoUrl) -> PendingLoad { PendingLoad { - bytes: ImageBytes::InProgress(vec![]), + bytes: ImageBytes::InProgress(vec!()), metadata: None, result: None, - listeners: vec![], + listeners: vec!(), url: url, final_url: None, } @@ -312,24 +337,20 @@ impl ImageCacheStore { }; match load_result { - LoadResult::Loaded(ref mut image) => { - set_webrender_image_key(&self.webrender_api, image) - }, - LoadResult::PlaceholderLoaded(..) | LoadResult::None => {}, + LoadResult::Loaded(ref mut image) => set_webrender_image_key(&self.webrender_api, image), + LoadResult::PlaceholderLoaded(..) | LoadResult::None => {} } let url = pending_load.final_url.clone(); let image_response = match load_result { LoadResult::Loaded(image) => ImageResponse::Loaded(Arc::new(image), url.unwrap()), - LoadResult::PlaceholderLoaded(image) => { - ImageResponse::PlaceholderLoaded(image, self.placeholder_url.clone()) - }, + LoadResult::PlaceholderLoaded(image) => + ImageResponse::PlaceholderLoaded(image, self.placeholder_url.clone()), LoadResult::None => ImageResponse::None, }; let completed_load = CompletedLoad::new(image_response.clone(), key); - self.completed_loads - .insert(pending_load.url.into(), completed_load); + self.completed_loads.insert(pending_load.url.into(), completed_load); for listener in pending_load.listeners { listener.respond(image_response.clone()); @@ -338,20 +359,21 @@ impl ImageCacheStore { /// Return a completed image if it exists, or None if there is no complete load /// or the complete load is not fully decoded or is unavailable. - fn get_completed_image_if_available( - &self, - url: &ServoUrl, - placeholder: UsePlaceholder, - ) -> Option> { + fn get_completed_image_if_available(&self, + url: &ServoUrl, + placeholder: UsePlaceholder) + -> Option> { self.completed_loads.get(url).map(|completed_load| { match (&completed_load.image_response, placeholder) { (&ImageResponse::Loaded(ref image, ref url), _) | - (&ImageResponse::PlaceholderLoaded(ref image, ref url), UsePlaceholder::Yes) => Ok( - ImageOrMetadataAvailable::ImageAvailable(image.clone(), url.clone()), - ), + (&ImageResponse::PlaceholderLoaded(ref image, ref url), UsePlaceholder::Yes) => { + Ok(ImageOrMetadataAvailable::ImageAvailable(image.clone(), url.clone())) + } (&ImageResponse::PlaceholderLoaded(_, _), UsePlaceholder::No) | (&ImageResponse::None, _) | - (&ImageResponse::MetadataLoaded(_), _) => Err(ImageState::LoadError), + (&ImageResponse::MetadataLoaded(_), _) => { + Err(ImageState::LoadError) + } } }) } @@ -384,19 +406,18 @@ impl ImageCache for ImageCacheImpl { placeholder_image: get_placeholder_image(&webrender_api, &rippy_data).ok(), placeholder_url: ServoUrl::parse("chrome://resources/rippy.png").unwrap(), webrender_api: webrender_api, - })), + })) } } /// Return any available metadata or image for the given URL, /// or an indication that the image is not yet available if it is in progress, /// or else reserve a slot in the cache for the URL if the consumer can request images. - fn find_image_or_metadata( - &self, - url: ServoUrl, - use_placeholder: UsePlaceholder, - can_request: CanRequestImages, - ) -> Result { + fn find_image_or_metadata(&self, + url: ServoUrl, + use_placeholder: UsePlaceholder, + can_request: CanRequestImages) + -> Result { debug!("Find image or metadata for {}", url); let mut store = self.store.lock().unwrap(); if let Some(result) = store.get_completed_image_if_available(&url, use_placeholder) { @@ -411,24 +432,24 @@ impl ImageCache for ImageCacheImpl { (&Some(Ok(_)), _) => { debug!("Sync decoding {} ({:?})", url, key); decode_bytes_sync(key, &pl.bytes.as_slice()) - }, + } (&None, &Some(ref meta)) => { debug!("Metadata available for {} ({:?})", url, key); - return Ok(ImageOrMetadataAvailable::MetadataAvailable(meta.clone())); - }, + return Ok(ImageOrMetadataAvailable::MetadataAvailable(meta.clone())) + } (&Some(Err(_)), _) | (&None, &None) => { debug!("{} ({:?}) is still pending", url, key); return Err(ImageState::Pending(key)); - }, + } }, CacheResult::Miss(Some((key, _pl))) => { debug!("Should be requesting {} ({:?})", url, key); return Err(ImageState::NotRequested(key)); - }, + } CacheResult::Miss(None) => { debug!("Couldn't find an entry for {}", url); return Err(ImageState::LoadError); - }, + } } }; @@ -470,15 +491,17 @@ impl ImageCache for ImageCacheImpl { let mut store = self.store.lock().unwrap(); let pending_load = store.pending_loads.get_by_key_mut(&id).unwrap(); let metadata = match response { - Ok(meta) => Some(match meta { - FetchMetadata::Unfiltered(m) => m, - FetchMetadata::Filtered { unsafe_, .. } => unsafe_, - }), + Ok(meta) => { + Some(match meta { + FetchMetadata::Unfiltered(m) => m, + FetchMetadata::Filtered { unsafe_, .. } => unsafe_, + }) + }, Err(_) => None, }; let final_url = metadata.as_ref().map(|m| m.final_url.clone()); pending_load.final_url = final_url; - }, + } (FetchResponseMsg::ProcessResponseChunk(data), _) => { debug!("Got some data for {:?}", id); let mut store = self.store.lock().unwrap(); @@ -488,17 +511,16 @@ impl ImageCache for ImageCacheImpl { if let None = pending_load.metadata { if let Ok(metadata) = load_from_buf(&pending_load.bytes.as_slice()) { let dimensions = metadata.dimensions(); - let img_metadata = ImageMetadata { - width: dimensions.width, - height: dimensions.height, - }; + let img_metadata = ImageMetadata { width: dimensions.width, + height: dimensions.height }; for listener in &pending_load.listeners { - listener.respond(ImageResponse::MetadataLoaded(img_metadata.clone())); + listener.respond( + ImageResponse::MetadataLoaded(img_metadata.clone())); } pending_load.metadata = Some(img_metadata); } } - }, + } (FetchResponseMsg::ProcessResponseEOF(result), key) => { debug!("Received EOF for {:?}", key); match result { @@ -517,20 +539,20 @@ impl ImageCache for ImageCacheImpl { debug!("Image decoded"); local_store.lock().unwrap().handle_decoder(msg); }); - }, + } Err(_) => { debug!("Processing error for {:?}", key); let mut store = self.store.lock().unwrap(); match store.placeholder_image.clone() { - Some(placeholder_image) => store.complete_load( - id, - LoadResult::PlaceholderLoaded(placeholder_image), - ), + Some(placeholder_image) => { + store.complete_load( + id, LoadResult::PlaceholderLoaded(placeholder_image)) + } None => store.complete_load(id, LoadResult::None), } - }, + } } - }, + } } } diff --git a/components/net/lib.rs b/components/net/lib.rs index 7f36629d3062..ab5c3bc74a2b 100644 --- a/components/net/lib.rs +++ b/components/net/lib.rs @@ -4,18 +4,44 @@ #![deny(unsafe_code)] +extern crate base64; +extern crate brotli; +extern crate cookie as cookie_rs; +extern crate devtools_traits; +extern crate embedder_traits; +extern crate flate2; +extern crate hyper; +extern crate hyper_openssl; +extern crate hyper_serde; +extern crate immeta; +extern crate ipc_channel; #[macro_use] extern crate lazy_static; +#[macro_use] extern crate log; +extern crate malloc_size_of; +#[macro_use] extern crate malloc_size_of_derive; +#[macro_use] #[no_link] extern crate matches; #[macro_use] -extern crate log; -#[macro_use] -extern crate malloc_size_of_derive; -#[macro_use] -extern crate matches; +extern crate mime; +extern crate mime_guess; +extern crate msg; +extern crate net_traits; +extern crate openssl; #[macro_use] extern crate profile_traits; -#[macro_use] -extern crate serde; +#[macro_use] extern crate serde; +extern crate serde_json; +extern crate servo_allocator; +extern crate servo_arc; +extern crate servo_channel; +extern crate servo_config; +extern crate servo_url; +extern crate time; +extern crate unicase; +extern crate url; +extern crate uuid; +extern crate webrender_api; +extern crate ws; mod blob_loader; pub mod connector; @@ -41,6 +67,6 @@ pub mod fetch { /// A module for re-exports of items used in unit tests. pub mod test { - pub use crate::hosts::{parse_hostsfile, replace_host_table}; - pub use crate::http_loader::HttpState; + pub use http_loader::HttpState; + pub use hosts::{replace_host_table, parse_hostsfile}; } diff --git a/components/net/mime_classifier.rs b/components/net/mime_classifier.rs index 432cb36dee5c..f59dc2b925d6 100644 --- a/components/net/mime_classifier.rs +++ b/components/net/mime_classifier.rs @@ -2,8 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use mime::{self, Mime}; +use hyper::mime::TopLevel; use net_traits::LoadContext; +use std::borrow::ToOwned; pub struct MimeClassifier { image_classifier: GroupedClassifier, @@ -25,17 +26,16 @@ pub enum MediaType { pub enum ApacheBugFlag { On, - Off, + Off } impl ApacheBugFlag { /// pub fn from_content_type(last_raw_content_type: &[u8]) -> ApacheBugFlag { - if last_raw_content_type == b"text/plain" || - last_raw_content_type == b"text/plain; charset=ISO-8859-1" || - last_raw_content_type == b"text/plain; charset=iso-8859-1" || - last_raw_content_type == b"text/plain; charset=UTF-8" - { + if last_raw_content_type == b"text/plain" + || last_raw_content_type == b"text/plain; charset=ISO-8859-1" + || last_raw_content_type == b"text/plain; charset=iso-8859-1" + || last_raw_content_type == b"text/plain; charset=UTF-8" { ApacheBugFlag::On } else { ApacheBugFlag::Off @@ -46,68 +46,60 @@ impl ApacheBugFlag { #[derive(PartialEq)] pub enum NoSniffFlag { On, - Off, + Off } +pub type MimeType = (TopLevel, String); + + impl MimeClassifier { //Performs MIME Type Sniffing Algorithm (sections 7 and 8) - pub fn classify<'a>( - &'a self, - context: LoadContext, - no_sniff_flag: NoSniffFlag, - apache_bug_flag: ApacheBugFlag, - supplied_type: &Option, - data: &'a [u8], - ) -> Mime { - let supplied_type_or_octet_stream = supplied_type - .clone() - .unwrap_or(mime::APPLICATION_OCTET_STREAM); + pub fn classify(&self, + context: LoadContext, + no_sniff_flag: NoSniffFlag, + apache_bug_flag: ApacheBugFlag, + supplied_type: &Option, + data: &[u8]) -> MimeType { + let supplied_type_or_octet_stream = supplied_type.clone() + .unwrap_or((TopLevel::Application, + "octet-stream".to_owned())); match context { LoadContext::Browsing => match *supplied_type { None => self.sniff_unknown_type(no_sniff_flag, data), Some(ref supplied_type) => { - if MimeClassifier::is_explicit_unknown(supplied_type) { + let &(ref media_type, ref media_subtype) = supplied_type; + if MimeClassifier::is_explicit_unknown(media_type, media_subtype) { self.sniff_unknown_type(no_sniff_flag, data) } else { match no_sniff_flag { NoSniffFlag::On => supplied_type.clone(), NoSniffFlag::Off => match apache_bug_flag { ApacheBugFlag::On => self.sniff_text_or_data(data), - ApacheBugFlag::Off => { - match MimeClassifier::get_media_type(supplied_type) { - Some(MediaType::Html) => { - self.feeds_classifier.classify(data) - }, - Some(MediaType::Image) => { - self.image_classifier.classify(data) - }, - Some(MediaType::AudioVideo) => { - self.audio_video_classifier.classify(data) - }, - Some(MediaType::Xml) | None => None, - } - .unwrap_or(supplied_type.clone()) - }, - }, + ApacheBugFlag::Off => match MimeClassifier::get_media_type(media_type, + media_subtype) { + Some(MediaType::Html) => self.feeds_classifier.classify(data), + Some(MediaType::Image) => self.image_classifier.classify(data), + Some(MediaType::AudioVideo) => self.audio_video_classifier.classify(data), + Some(MediaType::Xml) | None => None, + }.unwrap_or(supplied_type.clone()) + } } } - }, + } }, LoadContext::Image => { // Section 8.2 Sniffing an image context match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.image_classifier.classify(data), - } - .unwrap_or(supplied_type_or_octet_stream) + }.unwrap_or(supplied_type_or_octet_stream) }, LoadContext::AudioVideo => { // Section 8.3 Sniffing an image context match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.audio_video_classifier.classify(data), - } - .unwrap_or(supplied_type_or_octet_stream) + }.unwrap_or(supplied_type_or_octet_stream) }, LoadContext::Plugin => { // 8.4 Sniffing in a plugin context @@ -115,7 +107,7 @@ impl MimeClassifier { // This section was *not* finalized in the specs at the time // of this implementation. match *supplied_type { - None => mime::APPLICATION_OCTET_STREAM, + None => (TopLevel::Application, "octet-stream".to_owned()), _ => supplied_type_or_octet_stream, } }, @@ -125,7 +117,7 @@ impl MimeClassifier { // This section was *not* finalized in the specs at the time // of this implementation. match *supplied_type { - None => mime::TEXT_CSS, + None => (TopLevel::Text, "css".to_owned()), _ => supplied_type_or_octet_stream, } }, @@ -135,7 +127,7 @@ impl MimeClassifier { // This section was *not* finalized in the specs at the time // of this implementation. match *supplied_type { - None => mime::TEXT_JAVASCRIPT, + None => (TopLevel::Text, "javascript".to_owned()), _ => supplied_type_or_octet_stream, } }, @@ -144,37 +136,36 @@ impl MimeClassifier { match MimeClassifier::maybe_get_media_type(supplied_type) { Some(MediaType::Xml) => None, _ => self.font_classifier.classify(data), - } - .unwrap_or(supplied_type_or_octet_stream) + }.unwrap_or(supplied_type_or_octet_stream) }, LoadContext::TextTrack => { // 8.8 Sniffing in a text track context // // This section was *not* finalized in the specs at the time // of this implementation. - "text/vtt".parse().unwrap() + (TopLevel::Text, "vtt".to_owned()) }, LoadContext::CacheManifest => { // 8.9 Sniffing in a cache manifest context // // This section was *not* finalized in the specs at the time // of this implementation. - "text/cache-manifest".parse().unwrap() + (TopLevel::Text, "cache-manifest".to_owned()) }, } } pub fn new() -> MimeClassifier { - MimeClassifier { - image_classifier: GroupedClassifier::image_classifer(), - audio_video_classifier: GroupedClassifier::audio_video_classifier(), - scriptable_classifier: GroupedClassifier::scriptable_classifier(), - plaintext_classifier: GroupedClassifier::plaintext_classifier(), - archive_classifier: GroupedClassifier::archive_classifier(), - binary_or_plaintext: BinaryOrPlaintextClassifier, - feeds_classifier: FeedsClassifier, - font_classifier: GroupedClassifier::font_classifier(), - } + MimeClassifier { + image_classifier: GroupedClassifier::image_classifer(), + audio_video_classifier: GroupedClassifier::audio_video_classifier(), + scriptable_classifier: GroupedClassifier::scriptable_classifier(), + plaintext_classifier: GroupedClassifier::plaintext_classifier(), + archive_classifier: GroupedClassifier::archive_classifier(), + binary_or_plaintext: BinaryOrPlaintextClassifier, + feeds_classifier: FeedsClassifier, + font_classifier: GroupedClassifier::font_classifier() + } } pub fn validate(&self) -> Result<(), String> { @@ -190,7 +181,7 @@ impl MimeClassifier { } //some sort of iterator over the classifiers might be better? - fn sniff_unknown_type(&self, no_sniff_flag: NoSniffFlag, data: &[u8]) -> Mime { + fn sniff_unknown_type(&self, no_sniff_flag: NoSniffFlag, data: &[u8]) -> MimeType { let should_sniff_scriptable = no_sniff_flag == NoSniffFlag::Off; let sniffed = if should_sniff_scriptable { self.scriptable_classifier.classify(data) @@ -198,8 +189,7 @@ impl MimeClassifier { None }; - sniffed - .or_else(|| self.plaintext_classifier.classify(data)) + sniffed.or_else(|| self.plaintext_classifier.classify(data)) .or_else(|| self.image_classifier.classify(data)) .or_else(|| self.audio_video_classifier.classify(data)) .or_else(|| self.archive_classifier.classify(data)) @@ -207,62 +197,72 @@ impl MimeClassifier { .expect("BinaryOrPlaintextClassifier always succeeds") } - fn sniff_text_or_data<'a>(&'a self, data: &'a [u8]) -> Mime { - self.binary_or_plaintext - .classify(data) - .expect("BinaryOrPlaintextClassifier always succeeds") + fn sniff_text_or_data(&self, data: &[u8]) -> MimeType { + self.binary_or_plaintext.classify(data).expect("BinaryOrPlaintextClassifier always succeeds") } - fn is_xml(mt: &Mime) -> bool { - mt.suffix() == Some(mime::XML) || - (mt.type_() == mime::APPLICATION && mt.subtype() == mime::XML) || - (mt.type_() == mime::TEXT && mt.subtype() == mime::XML) + fn is_xml(tp: &TopLevel, sub_tp: &str) -> bool { + sub_tp.ends_with("+xml") || + match (tp, sub_tp) { + (&TopLevel::Application, "xml") | (&TopLevel::Text, "xml") => true, + _ => false + } } - fn is_html(mt: &Mime) -> bool { - mt.type_() == mime::TEXT && mt.subtype() == mime::HTML + fn is_html(tp: &TopLevel, sub_tp: &str) -> bool { + *tp == TopLevel::Text && sub_tp == "html" } - fn is_image(mt: &Mime) -> bool { - mt.type_() == mime::IMAGE + fn is_image(tp: &TopLevel) -> bool { + *tp == TopLevel::Image } - fn is_audio_video(mt: &Mime) -> bool { - mt.type_() == mime::AUDIO || - mt.type_() == mime::VIDEO || - mt.type_() == mime::APPLICATION && mt.subtype() == mime::OGG + fn is_audio_video(tp: &TopLevel, sub_tp: &str) -> bool { + *tp == TopLevel::Audio || + *tp == TopLevel::Video || + (*tp == TopLevel::Application && sub_tp == "ogg") } - fn is_explicit_unknown(mt: &Mime) -> bool { - mt.type_().as_str() == "unknown" && mt.subtype().as_str() == "unknown" || - mt.type_() == mime::APPLICATION && mt.subtype().as_str() == "unknown" || - mt.type_() == mime::STAR && mt.subtype() == mime::STAR + fn is_explicit_unknown(tp: &TopLevel, sub_tp: &str) -> bool { + if let TopLevel::Ext(ref e) = *tp { + return e == "unknown" && sub_tp == "unknown"; + } + match (tp, sub_tp) { + (&TopLevel::Application, "unknown") | + (&TopLevel::Star, "*") => true, + _ => false + } } - fn get_media_type(mime: &Mime) -> Option { - if MimeClassifier::is_xml(&mime) { + fn get_media_type(media_type: &TopLevel, + media_subtype: &str) -> Option { + if MimeClassifier::is_xml(media_type, media_subtype) { Some(MediaType::Xml) - } else if MimeClassifier::is_html(&mime) { - Some(MediaType::Html) - } else if MimeClassifier::is_image(&mime) { + } else if MimeClassifier::is_html(media_type, media_subtype) { + Some(MediaType::Html) + } else if MimeClassifier::is_image(media_type) { Some(MediaType::Image) - } else if MimeClassifier::is_audio_video(&mime) { + } else if MimeClassifier::is_audio_video(media_type, media_subtype) { Some(MediaType::AudioVideo) } else { None } } - fn maybe_get_media_type(supplied_type: &Option) -> Option { - supplied_type - .as_ref() - .and_then(|ref mime| MimeClassifier::get_media_type(mime)) + fn maybe_get_media_type(supplied_type: &Option) -> Option { + supplied_type.as_ref().and_then(|&(ref media_type, ref media_subtype)| { + MimeClassifier::get_media_type(media_type, media_subtype) + }) } } +pub fn as_string_option(tup: Option<(TopLevel, &'static str)>) -> Option { + tup.map(|(a, b)| (a.to_owned(), b.to_owned())) +} + //Interface used for composite types trait MIMEChecker { - fn classify(&self, data: &[u8]) -> Option; + fn classify(&self, data: &[u8]) -> Option; /// Validate the MIME checker configuration fn validate(&self) -> Result<(), String>; } @@ -271,7 +271,7 @@ trait Matches { fn matches(&mut self, matches: &[u8]) -> bool; } -impl<'a, T: Iterator + Clone> Matches for T { +impl <'a, T: Iterator + Clone> Matches for T { // Matching function that works on an iterator. // see if the next matches.len() bytes in data_iterator equal matches // move iterator and return true or just return false @@ -289,7 +289,7 @@ impl<'a, T: Iterator + Clone> Matches for T { fn matches(&mut self, matches: &[u8]) -> bool { if self.clone().nth(matches.len()).is_none() { // there are less than matches.len() elements in self - return false; + return false } let result = self.clone().zip(matches).all(|(s, m)| *s == *m); if result { @@ -303,7 +303,7 @@ struct ByteMatcher { pattern: &'static [u8], mask: &'static [u8], leading_ignore: &'static [u8], - content_type: Mime, + content_type: (TopLevel, &'static str) } impl ByteMatcher { @@ -313,68 +313,65 @@ impl ByteMatcher { } else if data == self.pattern { Some(self.pattern.len()) } else { - data[..data.len() - self.pattern.len() + 1] - .iter() + data[..data.len() - self.pattern.len() + 1].iter() .position(|x| !self.leading_ignore.contains(x)) - .and_then(|start| { - if data[start..] - .iter() - .zip(self.pattern.iter()) - .zip(self.mask.iter()) - .all(|((&data, &pattern), &mask)| (data & mask) == pattern) - { + .and_then(|start| + if data[start..].iter() + .zip(self.pattern.iter()).zip(self.mask.iter()) + .all(|((&data, &pattern), &mask)| (data & mask) == pattern) { Some(start + self.pattern.len()) } else { None - } - }) + }) } } } impl MIMEChecker for ByteMatcher { - fn classify(&self, data: &[u8]) -> Option { - self.matches(data).map(|_| self.content_type.clone()) + fn classify(&self, data: &[u8]) -> Option { + self.matches(data).map(|_| { + (self.content_type.0.to_owned(), self.content_type.1.to_owned()) + }) } fn validate(&self) -> Result<(), String> { if self.pattern.len() == 0 { - return Err(format!("Zero length pattern for {:?}", self.content_type)); + return Err(format!( + "Zero length pattern for {}/{}", + self.content_type.0, self.content_type.1 + )) } if self.pattern.len() != self.mask.len() { return Err(format!( - "Unequal pattern and mask length for {:?}", - self.content_type - )); + "Unequal pattern and mask length for {}/{}", + self.content_type.0, self.content_type.1 + )) } - if self - .pattern - .iter() - .zip(self.mask.iter()) - .any(|(&pattern, &mask)| pattern & mask != pattern) - { + if self.pattern.iter().zip(self.mask.iter()).any( + |(&pattern, &mask)| pattern & mask != pattern + ) { return Err(format!( - "Pattern not pre-masked for {:?}", - self.content_type - )); + "Pattern not pre-masked for {}/{}", + self.content_type.0, self.content_type.1 + )) } Ok(()) } } struct TagTerminatedByteMatcher { - matcher: ByteMatcher, + matcher: ByteMatcher } impl MIMEChecker for TagTerminatedByteMatcher { - fn classify(&self, data: &[u8]) -> Option { - self.matcher.matches(data).and_then(|j| { + fn classify(&self, data: &[u8]) -> Option { + self.matcher.matches(data).and_then(|j| if j < data.len() && (data[j] == b' ' || data[j] == b'>') { - Some(self.matcher.content_type.clone()) + Some((self.matcher.content_type.0.to_owned(), + self.matcher.content_type.1.to_owned())) } else { None - } - }) + }) } fn validate(&self) -> Result<(), String> { @@ -390,10 +387,8 @@ impl Mp4Matcher { return false; } - let box_size = ((data[0] as u32) << 24 | - (data[1] as u32) << 16 | - (data[2] as u32) << 8 | - (data[3] as u32)) as usize; + let box_size = ((data[0] as u32) << 24 | (data[1] as u32) << 16 | + (data[2] as u32) << 8 | (data[3] as u32)) as usize; if (data.len() < box_size) || (box_size % 4 != 0) { return false; } @@ -404,15 +399,15 @@ impl Mp4Matcher { } let mp4 = [0x6D, 0x70, 0x34]; - data[8..].starts_with(&mp4) || data[16..box_size] - .chunks(4) - .any(|chunk| chunk.starts_with(&mp4)) + data[8..].starts_with(&mp4) || + data[16..box_size].chunks(4).any(|chunk| chunk.starts_with(&mp4)) } + } impl MIMEChecker for Mp4Matcher { - fn classify(&self, data: &[u8]) -> Option { + fn classify(&self, data: &[u8]) -> Option { if self.matches(data) { - Some("video/mp4".parse().unwrap()) + Some((TopLevel::Video, "mp4".to_owned())) } else { None } @@ -426,35 +421,34 @@ impl MIMEChecker for Mp4Matcher { struct BinaryOrPlaintextClassifier; impl BinaryOrPlaintextClassifier { - fn classify_impl(&self, data: &[u8]) -> Mime { + fn classify_impl(&self, data: &[u8]) -> (TopLevel, &'static str) { if data.starts_with(&[0xFFu8, 0xFEu8]) || - data.starts_with(&[0xFEu8, 0xFFu8]) || - data.starts_with(&[0xEFu8, 0xBBu8, 0xBFu8]) + data.starts_with(&[0xFEu8, 0xFFu8]) || + data.starts_with(&[0xEFu8, 0xBBu8, 0xBFu8]) { - mime::TEXT_PLAIN - } else if data.iter().any(|&x| { - x <= 0x08u8 || - x == 0x0Bu8 || - (x >= 0x0Eu8 && x <= 0x1Au8) || - (x >= 0x1Cu8 && x <= 0x1Fu8) - }) { - mime::APPLICATION_OCTET_STREAM + (TopLevel::Text, "plain") + } else if data.iter().any(|&x| x <= 0x08u8 || + x == 0x0Bu8 || + (x >= 0x0Eu8 && x <= 0x1Au8) || + (x >= 0x1Cu8 && x <= 0x1Fu8)) { + (TopLevel::Application, "octet-stream") } else { - mime::TEXT_PLAIN + (TopLevel::Text, "plain") } } } impl MIMEChecker for BinaryOrPlaintextClassifier { - fn classify(&self, data: &[u8]) -> Option { - Some(self.classify_impl(data)) + fn classify(&self, data: &[u8]) -> Option { + as_string_option(Some(self.classify_impl(data))) } fn validate(&self) -> Result<(), String> { Ok(()) } + } struct GroupedClassifier { - byte_matchers: Vec>, + byte_matchers: Vec>, } impl GroupedClassifier { fn image_classifer() -> GroupedClassifier { @@ -468,7 +462,7 @@ impl GroupedClassifier { Box::new(ByteMatcher::image_webp()), Box::new(ByteMatcher::image_png()), Box::new(ByteMatcher::image_jpeg()), - ], + ] } } fn audio_video_classifier() -> GroupedClassifier { @@ -482,8 +476,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::audio_midi()), Box::new(ByteMatcher::video_avi()), Box::new(ByteMatcher::audio_wave()), - Box::new(Mp4Matcher), - ], + Box::new(Mp4Matcher) + ] } } fn scriptable_classifier() -> GroupedClassifier { @@ -507,8 +501,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::text_html_p()), Box::new(ByteMatcher::text_html_comment()), Box::new(ByteMatcher::text_xml()), - Box::new(ByteMatcher::application_pdf()), - ], + Box::new(ByteMatcher::application_pdf()) + ] } } fn plaintext_classifier() -> GroupedClassifier { @@ -517,8 +511,8 @@ impl GroupedClassifier { Box::new(ByteMatcher::text_plain_utf_8_bom()), Box::new(ByteMatcher::text_plain_utf_16le_bom()), Box::new(ByteMatcher::text_plain_utf_16be_bom()), - Box::new(ByteMatcher::application_postscript()), - ], + Box::new(ByteMatcher::application_postscript()) + ] } } fn archive_classifier() -> GroupedClassifier { @@ -526,8 +520,8 @@ impl GroupedClassifier { byte_matchers: vec![ Box::new(ByteMatcher::application_x_gzip()), Box::new(ByteMatcher::application_zip()), - Box::new(ByteMatcher::application_x_rar_compressed()), - ], + Box::new(ByteMatcher::application_x_rar_compressed()) + ] } } @@ -539,12 +533,12 @@ impl GroupedClassifier { Box::new(ByteMatcher::open_type()), Box::new(ByteMatcher::true_type()), Box::new(ByteMatcher::application_vnd_ms_font_object()), - ], + ] } } } impl MIMEChecker for GroupedClassifier { - fn classify(&self, data: &[u8]) -> Option { + fn classify(&self, data: &[u8]) -> Option { self.byte_matchers .iter() .filter_map(|matcher| matcher.classify(data)) @@ -562,7 +556,7 @@ impl MIMEChecker for GroupedClassifier { enum Match { Start, DidNotMatch, - StartAndEnd, + StartAndEnd } impl Match { @@ -575,9 +569,7 @@ impl Match { } fn eats_until<'a, T>(matcher: &mut T, start: &[u8], end: &[u8]) -> Match -where - T: Iterator + Clone, -{ +where T: Iterator + Clone { if !matcher.matches(start) { Match::DidNotMatch } else if end.len() == 1 { @@ -599,7 +591,7 @@ where struct FeedsClassifier; impl FeedsClassifier { // Implements sniffing for mislabeled feeds (https://mimesniff.spec.whatwg.org/#sniffing-a-mislabeled-feed) - fn classify_impl(&self, data: &[u8]) -> Option { + fn classify_impl(&self, data: &[u8]) -> Option<(TopLevel, &'static str)> { // Step 4: can not be feed unless length is > 3 if data.len() < 3 { return None; @@ -621,40 +613,33 @@ impl FeedsClassifier { // Steps 5.2.1 to 5.2.4 match eats_until(&mut matcher, b"?", b"?>") - .chain(|| eats_until(&mut matcher, b"!--", b"-->")) - .chain(|| eats_until(&mut matcher, b"!", b">")) - { + .chain(|| eats_until(&mut matcher, b"!--", b"-->")) + .chain(|| eats_until(&mut matcher, b"!", b">")) { Match::StartAndEnd => continue, Match::DidNotMatch => {}, - Match::Start => return None, + Match::Start => return None } // Step 5.2.5 if matcher.matches(b"rss") { - return Some("application/rss+xml".parse().unwrap()); + return Some((TopLevel::Application, "rss+xml")); } // Step 5.2.6 if matcher.matches(b"feed") { - return Some("application/atom+xml".parse().unwrap()); + return Some((TopLevel::Application, "atom+xml")); } // Step 5.2.7 if matcher.matches(b"rdf:RDF") { while matcher.next().is_some() { - match eats_until( - &mut matcher, - b"http://purl.org/rss/1.0/", - b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", - ) - .chain(|| { - eats_until( - &mut matcher, - b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", - b"http://purl.org/rss/1.0/", - ) - }) { - Match::StartAndEnd => return Some("application/rss+xml".parse().unwrap()), + match eats_until(&mut matcher, + b"http://purl.org/rss/1.0/", + b"http://www.w3.org/1999/02/22-rdf-syntax-ns#") + .chain(|| eats_until(&mut matcher, + b"http://www.w3.org/1999/02/22-rdf-syntax-ns#", + b"http://purl.org/rss/1.0/")) { + Match::StartAndEnd => return Some((TopLevel::Application, "rss+xml")), Match::DidNotMatch => {}, - Match::Start => return None, + Match::Start => return None } } return None; @@ -664,8 +649,8 @@ impl FeedsClassifier { } impl MIMEChecker for FeedsClassifier { - fn classify(&self, data: &[u8]) -> Option { - self.classify_impl(data) + fn classify(&self, data: &[u8]) -> Option { + as_string_option(self.classify_impl(data)) } fn validate(&self) -> Result<(), String> { @@ -681,8 +666,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\x00\x00\x01\x00", mask: b"\xFF\xFF\xFF\xFF", - content_type: "image/x-icon".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Image, "x-icon"), + leading_ignore: &[] } } //A Windows Cursor signature. @@ -690,8 +675,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\x00\x00\x02\x00", mask: b"\xFF\xFF\xFF\xFF", - content_type: "image/x-icon".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Image, "x-icon"), + leading_ignore: &[] } } //The string "BM", a BMP signature. @@ -699,8 +684,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"BM", mask: b"\xFF\xFF", - content_type: mime::IMAGE_BMP, - leading_ignore: &[], + content_type: (TopLevel::Image, "bmp"), + leading_ignore: &[] } } //The string "GIF89a", a GIF signature. @@ -708,8 +693,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"GIF89a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: mime::IMAGE_GIF, - leading_ignore: &[], + content_type: (TopLevel::Image, "gif"), + leading_ignore: &[] } } //The string "GIF87a", a GIF signature. @@ -717,8 +702,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"GIF87a", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: mime::IMAGE_GIF, - leading_ignore: &[], + content_type: (TopLevel::Image, "gif"), + leading_ignore: &[] } } //The string "RIFF" followed by four bytes followed by the string "WEBPVP". @@ -726,8 +711,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WEBPVP", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: "image/webp".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Image, "webp"), + leading_ignore: &[] } } //An error-checking byte followed by the string "PNG" followed by CR LF SUB LF, the PNG @@ -736,8 +721,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\x89PNG\r\n\x1A\n", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: mime::IMAGE_PNG, - leading_ignore: &[], + content_type: (TopLevel::Image, "png"), + leading_ignore: &[] } } // The JPEG Start of Image marker followed by the indicator byte of another marker. @@ -745,8 +730,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\xFF\xD8\xFF", mask: b"\xFF\xFF\xFF", - content_type: mime::IMAGE_JPEG, - leading_ignore: &[], + content_type: (TopLevel::Image, "jpeg"), + leading_ignore: &[] } } //The WebM signature. [TODO: Use more bytes?] @@ -754,8 +739,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\x1A\x45\xDF\xA3", mask: b"\xFF\xFF\xFF\xFF", - content_type: "video/webm".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Video, "webm"), + leading_ignore: &[] } } //The string ".snd", the basic audio signature. @@ -763,17 +748,17 @@ impl ByteMatcher { ByteMatcher { pattern: b".snd", mask: b"\xFF\xFF\xFF\xFF", - content_type: "audio/basic".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Audio, "basic"), + leading_ignore: &[] } } //The string "FORM" followed by four bytes followed by the string "AIFF", the AIFF signature. fn audio_aiff() -> ByteMatcher { ByteMatcher { - pattern: b"FORM\x00\x00\x00\x00AIFF", - mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", - content_type: "audio/aiff".parse().unwrap(), - leading_ignore: &[], + pattern: b"FORM\x00\x00\x00\x00AIFF", + mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", + content_type: (TopLevel::Audio, "aiff"), + leading_ignore: &[] } } //The string "ID3", the ID3v2-tagged MP3 signature. @@ -781,8 +766,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"ID3", mask: b"\xFF\xFF\xFF", - content_type: "audio/mpeg".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Audio, "mpeg"), + leading_ignore: &[] } } //The string "OggS" followed by NUL, the Ogg container signature. @@ -790,8 +775,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"OggS\x00", mask: b"\xFF\xFF\xFF\xFF\xFF", - content_type: "application/ogg".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Application, "ogg"), + leading_ignore: &[] } } //The string "MThd" followed by four bytes representing the number 6 in 32 bits (big-endian), @@ -800,8 +785,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"MThd\x00\x00\x00\x06", mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: "audio/midi".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Audio, "midi"), + leading_ignore: &[] } } //The string "RIFF" followed by four bytes followed by the string "AVI ", the AVI signature. @@ -809,8 +794,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00AVI ", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", - content_type: "video/avi".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Video, "avi"), + leading_ignore: &[] } } // The string "RIFF" followed by four bytes followed by the string "WAVE", the WAVE signature. @@ -818,8 +803,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"RIFF\x00\x00\x00\x00WAVE", mask: b"\xFF\xFF\xFF\xFF\x00\x00\x00\x00\xFF\xFF\xFF\xFF", - content_type: "audio/wave".parse().unwrap(), - leading_ignore: &[], + content_type: (TopLevel::Audio, "wave"), + leading_ignore: &[] } } // doctype terminated with Tag terminating (TT) Byte @@ -828,9 +813,9 @@ impl ByteMatcher { matcher: ByteMatcher { pattern: b" TagTerminatedByteMatcher { - TagTerminatedByteMatcher { + TagTerminatedByteMatcher { matcher: ByteMatcher { pattern: b" TagTerminatedByteMatcher { TagTerminatedByteMatcher { matcher: ByteMatcher { - pattern: b" ByteMatcher { ByteMatcher { pattern: b"%!PS-Adobe-", - mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", - content_type: "application/postscript".parse().unwrap(), - leading_ignore: &[], + mask: b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + content_type: (TopLevel::Application, "postscript"), + leading_ignore: &[] } } // UTF-16BE BOM @@ -1134,8 +1119,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\xFE\xFF\x00\x00", mask: b"\xFF\xFF\x00\x00", - content_type: mime::TEXT_PLAIN, - leading_ignore: &[], + content_type: (TopLevel::Text, "plain"), + leading_ignore: &[] } } //UTF-16LE BOM @@ -1143,8 +1128,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\xFF\xFE\x00\x00", mask: b"\xFF\xFF\x00\x00", - content_type: mime::TEXT_PLAIN, - leading_ignore: &[], + content_type: (TopLevel::Text, "plain"), + leading_ignore: &[] } } //UTF-8 BOM @@ -1152,8 +1137,8 @@ impl ByteMatcher { ByteMatcher { pattern: b"\xEF\xBB\xBF\x00", mask: b"\xFF\xFF\xFF\x00", - content_type: mime::TEXT_PLAIN, - leading_ignore: &[], + content_type: (TopLevel::Text, "plain"), + leading_ignore: &[] } } } diff --git a/components/net/resource_thread.rs b/components/net/resource_thread.rs index 0ae1f5485254..cddf0cb0a0b7 100644 --- a/components/net/resource_thread.rs +++ b/components/net/resource_thread.rs @@ -3,35 +3,35 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A thread that takes a URL and streams back the binary data. - -use crate::connector::{create_http_client, create_ssl_connector_builder}; -use crate::cookie; -use crate::cookie_storage::CookieStorage; -use crate::fetch::cors_cache::CorsCache; -use crate::fetch::methods::{fetch, CancellationListener, FetchContext}; -use crate::filemanager_thread::FileManager; -use crate::hsts::HstsList; -use crate::http_cache::HttpCache; -use crate::http_loader::{http_redirect_fetch, HttpState, HANDLE}; -use crate::storage_thread::StorageThreadFactory; -use crate::websocket_loader; +use connector::{create_http_connector, create_ssl_client}; +use cookie; +use cookie_rs; +use cookie_storage::CookieStorage; use devtools_traits::DevtoolsControlMsg; -use embedder_traits::resources::{self, Resource}; use embedder_traits::EmbedderProxy; +use embedder_traits::resources::{self, Resource}; +use fetch::cors_cache::CorsCache; +use fetch::methods::{CancellationListener, FetchContext, fetch}; +use filemanager_thread::FileManager; +use hsts::HstsList; +use http_cache::HttpCache; +use http_loader::{HttpState, http_redirect_fetch}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcReceiver, IpcReceiverSet, IpcSender}; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; -use net_traits::request::{Request, RequestInit}; -use net_traits::response::{Response, ResponseInit}; -use net_traits::storage_thread::StorageThreadMsg; -use net_traits::WebSocketNetworkEvent; use net_traits::{CookieSource, CoreResourceThread}; use net_traits::{CoreResourceMsg, CustomResponseMediator, FetchChannels}; use net_traits::{FetchResponseMsg, ResourceThreads, WebSocketDomAction}; +use net_traits::WebSocketNetworkEvent; +use net_traits::request::{Request, RequestInit}; +use net_traits::response::{Response, ResponseInit}; +use net_traits::storage_thread::StorageThreadMsg; +use profile_traits::mem::{Report, ReportsChan, ReportKind}; use profile_traits::mem::ProfilerChan as MemProfilerChan; -use profile_traits::mem::{Report, ReportKind, ReportsChan}; use profile_traits::time::ProfilerChan; use serde::{Deserialize, Serialize}; +use serde_json; +use servo_allocator; use servo_channel::Sender; use servo_config::opts; use servo_url::ServoUrl; @@ -44,67 +44,63 @@ use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, RwLock}; use std::thread; +use storage_thread::StorageThreadFactory; +use websocket_loader; /// Returns a tuple of (public, private) senders to the new threads. -pub fn new_resource_threads( - user_agent: Cow<'static, str>, - devtools_chan: Option>, - time_profiler_chan: ProfilerChan, - mem_profiler_chan: MemProfilerChan, - embedder_proxy: EmbedderProxy, - config_dir: Option, -) -> (ResourceThreads, ResourceThreads) { +pub fn new_resource_threads(user_agent: Cow<'static, str>, + devtools_chan: Option>, + time_profiler_chan: ProfilerChan, + mem_profiler_chan: MemProfilerChan, + embedder_proxy: EmbedderProxy, + config_dir: Option) + -> (ResourceThreads, ResourceThreads) { let (public_core, private_core) = new_core_resource_thread( user_agent, devtools_chan, time_profiler_chan, mem_profiler_chan, embedder_proxy, - config_dir.clone(), - ); + config_dir.clone()); let storage: IpcSender = StorageThreadFactory::new(config_dir); - ( - ResourceThreads::new(public_core, storage.clone()), - ResourceThreads::new(private_core, storage), - ) + (ResourceThreads::new(public_core, storage.clone()), + ResourceThreads::new(private_core, storage)) } + /// Create a CoreResourceThread -pub fn new_core_resource_thread( - user_agent: Cow<'static, str>, - devtools_chan: Option>, - time_profiler_chan: ProfilerChan, - mem_profiler_chan: MemProfilerChan, - embedder_proxy: EmbedderProxy, - config_dir: Option, -) -> (CoreResourceThread, CoreResourceThread) { +pub fn new_core_resource_thread(user_agent: Cow<'static, str>, + devtools_chan: Option>, + time_profiler_chan: ProfilerChan, + mem_profiler_chan: MemProfilerChan, + embedder_proxy: EmbedderProxy, + config_dir: Option) + -> (CoreResourceThread, CoreResourceThread) { let (public_setup_chan, public_setup_port) = ipc::channel().unwrap(); let (private_setup_chan, private_setup_port) = ipc::channel().unwrap(); let (report_chan, report_port) = ipc::channel().unwrap(); - thread::Builder::new() - .name("ResourceManager".to_owned()) - .spawn(move || { - let resource_manager = CoreResourceManager::new( - user_agent, - devtools_chan, - time_profiler_chan, - embedder_proxy, - ); - - let mut channel_manager = ResourceChannelManager { - resource_manager: resource_manager, - config_dir: config_dir, - }; + thread::Builder::new().name("ResourceManager".to_owned()).spawn(move || { + let resource_manager = CoreResourceManager::new( + user_agent, devtools_chan, time_profiler_chan, embedder_proxy + ); + + let mut channel_manager = ResourceChannelManager { + resource_manager: resource_manager, + config_dir: config_dir, + }; - mem_profiler_chan.run_with_memory_reporting( - || (channel_manager.start(public_setup_port, private_setup_port, report_port)), - String::from("network-cache-reporter"), - report_chan, - |report_chan| report_chan, - ); - }) - .expect("Thread spawning failed"); + mem_profiler_chan.run_with_memory_reporting(|| ( + channel_manager.start( + public_setup_port, + private_setup_port, + report_port) + ), + String::from("network-cache-reporter"), + report_chan, + |report_chan| report_chan); + + }).expect("Thread spawning failed"); (public_setup_chan, private_setup_chan) } @@ -125,21 +121,26 @@ fn create_http_states(config_dir: Option<&Path>) -> (Arc, Arc fs::read_to_string(path).expect("Couldn't not find certificate file"), - None => resources::read_string(Resource::SSLCertificates), + Some(ref path) => { + fs::read_to_string(path).expect("Couldn't not find certificate file") + } + None => { + resources::read_string(Resource::SSLCertificates) + }, }; - let ssl_connector_builder = create_ssl_connector_builder(&certs); + let ssl_client = create_ssl_client(&certs); let http_state = HttpState { cookie_jar: RwLock::new(cookie_jar), auth_cache: RwLock::new(auth_cache), http_cache: RwLock::new(http_cache), hsts_list: RwLock::new(hsts_list), history_states: RwLock::new(HashMap::new()), - client: create_http_client(ssl_connector_builder, HANDLE.lock().unwrap().executor()), + ssl_client: ssl_client.clone(), + connector: create_http_connector(ssl_client), }; - let private_ssl_client = create_ssl_connector_builder(&certs); + let private_ssl_client = create_ssl_client(&certs); let private_http_state = HttpState::new(private_ssl_client); (Arc::new(http_state), Arc::new(private_http_state)) @@ -147,12 +148,10 @@ fn create_http_states(config_dir: Option<&Path>) -> (Arc, Arc, - private_receiver: IpcReceiver, - memory_reporter: IpcReceiver, - ) { + fn start(&mut self, + public_receiver: IpcReceiver, + private_receiver: IpcReceiver, + memory_reporter: IpcReceiver) { let (public_http_state, private_http_state) = create_http_states(self.config_dir.as_ref().map(Deref::deref)); @@ -166,7 +165,7 @@ impl ResourceChannelManager { // Handles case where profiler thread shuts down before resource thread. match receiver { ipc::IpcSelectionResult::ChannelClosed(..) => continue, - _ => {}, + _ => {} } let (id, data) = receiver.unwrap(); // If message is memory report, get the size_of of public and private http caches @@ -192,12 +191,10 @@ impl ResourceChannelManager { } } - fn process_report( - &mut self, - msg: ReportsChan, - public_http_state: &Arc, - private_http_state: &Arc, - ) { + fn process_report(&mut self, + msg: ReportsChan, + public_http_state: &Arc, + private_http_state: &Arc) { let mut ops = MallocSizeOfOps::new(servo_allocator::usable_size, None, None); let public_cache = public_http_state.http_cache.read().unwrap(); let private_cache = private_http_state.http_cache.read().unwrap(); @@ -205,95 +202,74 @@ impl ResourceChannelManager { let public_report = Report { path: path!["memory-cache", "public"], kind: ReportKind::ExplicitJemallocHeapSize, - size: public_cache.size_of(&mut ops), + size: public_cache.size_of(&mut ops) }; let private_report = Report { path: path!["memory-cache", "private"], kind: ReportKind::ExplicitJemallocHeapSize, - size: private_cache.size_of(&mut ops), + size: private_cache.size_of(&mut ops) }; - msg.send(vec![public_report, private_report]); + msg.send(vec!(public_report, private_report)); } /// Returns false if the thread should exit. - fn process_msg(&mut self, msg: CoreResourceMsg, http_state: &Arc) -> bool { + fn process_msg(&mut self, + msg: CoreResourceMsg, + http_state: &Arc) -> bool { match msg { - CoreResourceMsg::Fetch(req_init, channels) => match channels { - FetchChannels::ResponseMsg(sender, cancel_chan) => { - self.resource_manager - .fetch(req_init, None, sender, http_state, cancel_chan) - }, - FetchChannels::WebSocket { - event_sender, - action_receiver, - } => self.resource_manager.websocket_connect( - req_init, - event_sender, - action_receiver, - http_state, - ), - }, - CoreResourceMsg::FetchRedirect(req_init, res_init, sender, cancel_chan) => self - .resource_manager - .fetch(req_init, Some(res_init), sender, http_state, cancel_chan), - CoreResourceMsg::SetCookieForUrl(request, cookie, source) => self - .resource_manager - .set_cookie_for_url(&request, cookie.into_inner(), source, http_state), + CoreResourceMsg::Fetch(req_init, channels) => { + match channels { + FetchChannels::ResponseMsg(sender, cancel_chan) => + self.resource_manager.fetch(req_init, None, sender, http_state, cancel_chan), + FetchChannels::WebSocket { event_sender, action_receiver } => + self.resource_manager.websocket_connect(req_init, event_sender, action_receiver, http_state), + } + } + CoreResourceMsg::FetchRedirect(req_init, res_init, sender, cancel_chan) => + self.resource_manager.fetch(req_init, Some(res_init), sender, http_state, cancel_chan), + CoreResourceMsg::SetCookieForUrl(request, cookie, source) => + self.resource_manager.set_cookie_for_url(&request, cookie.into_inner(), source, http_state), CoreResourceMsg::SetCookiesForUrl(request, cookies, source) => { for cookie in cookies { - self.resource_manager.set_cookie_for_url( - &request, - cookie.into_inner(), - source, - http_state, - ); + self.resource_manager.set_cookie_for_url(&request, cookie.into_inner(), source, http_state); } - }, + } CoreResourceMsg::GetCookiesForUrl(url, consumer, source) => { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); - consumer - .send(cookie_jar.cookies_for_url(&url, source)) - .unwrap(); - }, + consumer.send(cookie_jar.cookies_for_url(&url, source)).unwrap(); + } CoreResourceMsg::NetworkMediator(mediator_chan) => { self.resource_manager.swmanager_chan = Some(mediator_chan) - }, + } CoreResourceMsg::GetCookiesDataForUrl(url, consumer, source) => { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); - let cookies = cookie_jar - .cookies_data_for_url(&url, source) - .map(Serde) - .collect(); + let cookies = cookie_jar.cookies_data_for_url(&url, source).map(Serde).collect(); consumer.send(cookies).unwrap(); - }, + } CoreResourceMsg::GetHistoryState(history_state_id, consumer) => { let history_states = http_state.history_states.read().unwrap(); - consumer - .send(history_states.get(&history_state_id).cloned()) - .unwrap(); - }, + consumer.send(history_states.get(&history_state_id).cloned()).unwrap(); + } CoreResourceMsg::SetHistoryState(history_state_id, history_state) => { let mut history_states = http_state.history_states.write().unwrap(); history_states.insert(history_state_id, history_state); - }, + } CoreResourceMsg::RemoveHistoryStates(states_to_remove) => { let mut history_states = http_state.history_states.write().unwrap(); for history_state in states_to_remove { history_states.remove(&history_state); } - }, + } CoreResourceMsg::Synchronize(sender) => { let _ = sender.send(()); - }, + } CoreResourceMsg::ToFileManager(msg) => self.resource_manager.filemanager.handle(msg), CoreResourceMsg::Exit(sender) => { if let Some(ref config_dir) = self.config_dir { match http_state.auth_cache.read() { - Ok(auth_cache) => { - write_json_to_file(&*auth_cache, config_dir, "auth_cache.json") - }, + Ok(auth_cache) => write_json_to_file(&*auth_cache, config_dir, "auth_cache.json"), Err(_) => warn!("Error writing auth cache to disk"), } match http_state.cookie_jar.read() { @@ -307,15 +283,14 @@ impl ResourceChannelManager { } let _ = sender.send(()); return false; - }, + } } true } } pub fn read_json_from_file(data: &mut T, config_dir: &Path, filename: &str) -where - T: for<'de> Deserialize<'de>, + where T: for<'de> Deserialize<'de> { let path = config_dir.join(filename); let display = path.display(); @@ -330,11 +305,10 @@ where let mut string_buffer: String = String::new(); match file.read_to_string(&mut string_buffer) { - Err(why) => panic!( - "couldn't read from {}: {}", - display, - Error::description(&why) - ), + Err(why) => { + panic!("couldn't read from {}: {}", display, + Error::description(&why)) + }, Ok(_) => println!("successfully read from {}", display), } @@ -345,8 +319,7 @@ where } pub fn write_json_to_file(data: &T, config_dir: &Path, filename: &str) -where - T: Serialize, + where T: Serialize { let json_encoded: String; match serde_json::to_string_pretty(&data) { @@ -357,21 +330,22 @@ where let display = path.display(); let mut file = match File::create(&path) { - Err(why) => panic!("couldn't create {}: {}", display, Error::description(&why)), + Err(why) => panic!("couldn't create {}: {}", + display, + Error::description(&why)), Ok(file) => file, }; match file.write_all(json_encoded.as_bytes()) { - Err(why) => panic!( - "couldn't write to {}: {}", - display, - Error::description(&why) - ), + Err(why) => { + panic!("couldn't write to {}: {}", display, + Error::description(&why)) + }, Ok(_) => println!("successfully wrote to {}", display), } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct AuthCacheEntry { pub user_name: String, pub password: String, @@ -381,12 +355,12 @@ impl AuthCache { pub fn new() -> AuthCache { AuthCache { version: 1, - entries: HashMap::new(), + entries: HashMap::new() } } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct AuthCache { pub version: u32, pub entries: HashMap, @@ -400,12 +374,10 @@ pub struct CoreResourceManager { } impl CoreResourceManager { - pub fn new( - user_agent: Cow<'static, str>, - devtools_channel: Option>, - _profiler_chan: ProfilerChan, - embedder_proxy: EmbedderProxy, - ) -> CoreResourceManager { + pub fn new(user_agent: Cow<'static, str>, + devtools_channel: Option>, + _profiler_chan: ProfilerChan, + embedder_proxy: EmbedderProxy) -> CoreResourceManager { CoreResourceManager { user_agent: user_agent, devtools_chan: devtools_channel, @@ -414,67 +386,55 @@ impl CoreResourceManager { } } - fn set_cookie_for_url( - &mut self, - request: &ServoUrl, - cookie: cookie_rs::Cookie<'static>, - source: CookieSource, - http_state: &Arc, - ) { + fn set_cookie_for_url(&mut self, request: &ServoUrl, + cookie: cookie_rs::Cookie<'static>, + source: CookieSource, + http_state: &Arc) { if let Some(cookie) = cookie::Cookie::new_wrapped(cookie, request, source) { let mut cookie_jar = http_state.cookie_jar.write().unwrap(); cookie_jar.push(cookie, request, source) } } - fn fetch( - &self, - req_init: RequestInit, - res_init_: Option, - mut sender: IpcSender, - http_state: &Arc, - cancel_chan: Option>, - ) { + fn fetch(&self, + req_init: RequestInit, + res_init_: Option, + mut sender: IpcSender, + http_state: &Arc, + cancel_chan: Option>) { let http_state = http_state.clone(); let ua = self.user_agent.clone(); let dc = self.devtools_chan.clone(); let filemanager = self.filemanager.clone(); - thread::Builder::new() - .name(format!("fetch thread for {}", req_init.url)) - .spawn(move || { - let mut request = Request::from_init(req_init); - // XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed) - // todo load context / mimesniff in fetch - // todo referrer policy? - // todo service worker stuff - let context = FetchContext { - state: http_state, - user_agent: ua, - devtools_chan: dc, - filemanager: filemanager, - cancellation_listener: Arc::new(Mutex::new(CancellationListener::new( - cancel_chan, - ))), - }; - - match res_init_ { - Some(res_init) => { - let response = Response::from_init(res_init); - http_redirect_fetch( - &mut request, - &mut CorsCache::new(), - response, - true, - &mut sender, - &mut None, - &context, - ); - }, - None => fetch(&mut request, &mut sender, &context), - }; - }) - .expect("Thread spawning failed"); + thread::Builder::new().name(format!("fetch thread for {}", req_init.url)).spawn(move || { + let mut request = Request::from_init(req_init); + // XXXManishearth: Check origin against pipeline id (also ensure that the mode is allowed) + // todo load context / mimesniff in fetch + // todo referrer policy? + // todo service worker stuff + let context = FetchContext { + state: http_state, + user_agent: ua, + devtools_chan: dc, + filemanager: filemanager, + cancellation_listener: Arc::new(Mutex::new(CancellationListener::new(cancel_chan))), + }; + + match res_init_ { + Some(res_init) => { + let response = Response::from_init(res_init); + http_redirect_fetch(&mut request, + &mut CorsCache::new(), + response, + true, + &mut sender, + &mut None, + &context); + }, + None => fetch(&mut request, &mut sender, &context), + }; + }).expect("Thread spawning failed"); } fn websocket_connect( @@ -482,7 +442,7 @@ impl CoreResourceManager { request: RequestInit, event_sender: IpcSender, action_receiver: IpcReceiver, - http_state: &Arc, + http_state: &Arc ) { websocket_loader::init(request, event_sender, action_receiver, http_state.clone()); } diff --git a/components/net/storage_thread.rs b/components/net/storage_thread.rs index 48a5043a994f..5a336d2ea7ae 100644 --- a/components/net/storage_thread.rs +++ b/components/net/storage_thread.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::resource_thread; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use net_traits::storage_thread::{StorageThreadMsg, StorageType}; +use resource_thread; use servo_url::ServoUrl; use std::borrow::ToOwned; use std::collections::BTreeMap; @@ -22,12 +22,9 @@ impl StorageThreadFactory for IpcSender { /// Create a storage thread fn new(config_dir: Option) -> IpcSender { let (chan, port) = ipc::channel().unwrap(); - thread::Builder::new() - .name("StorageManager".to_owned()) - .spawn(move || { - StorageManager::new(port, config_dir).start(); - }) - .expect("Thread spawning failed"); + thread::Builder::new().name("StorageManager".to_owned()).spawn(move || { + StorageManager::new(port, config_dir).start(); + }).expect("Thread spawning failed"); chan } } @@ -40,7 +37,9 @@ struct StorageManager { } impl StorageManager { - fn new(port: IpcReceiver, config_dir: Option) -> StorageManager { + fn new(port: IpcReceiver, + config_dir: Option) + -> StorageManager { let mut local_data = HashMap::new(); if let Some(ref config_dir) = config_dir { resource_thread::read_json_from_file(&mut local_data, config_dir, "local_data.json"); @@ -60,33 +59,33 @@ impl StorageManager { match self.port.recv().unwrap() { StorageThreadMsg::Length(sender, url, storage_type) => { self.length(sender, url, storage_type) - }, + } StorageThreadMsg::Key(sender, url, storage_type, index) => { self.key(sender, url, storage_type, index) - }, + } StorageThreadMsg::Keys(sender, url, storage_type) => { self.keys(sender, url, storage_type) - }, + } StorageThreadMsg::SetItem(sender, url, storage_type, name, value) => { self.set_item(sender, url, storage_type, name, value); self.save_state() - }, + } StorageThreadMsg::GetItem(sender, url, storage_type, name) => { self.request_item(sender, url, storage_type, name) - }, + } StorageThreadMsg::RemoveItem(sender, url, storage_type, name) => { self.remove_item(sender, url, storage_type, name); self.save_state() - }, + } StorageThreadMsg::Clear(sender, url, storage_type) => { self.clear(sender, url, storage_type); self.save_state() - }, + } StorageThreadMsg::Exit(sender) => { // Nothing to do since we save localstorage set eagerly. let _ = sender.send(()); - break; - }, + break + } } } } @@ -97,56 +96,49 @@ impl StorageManager { } } - fn select_data( - &self, - storage_type: StorageType, - ) -> &HashMap)> { + fn select_data(&self, storage_type: StorageType) + -> &HashMap)> { match storage_type { StorageType::Session => &self.session_data, - StorageType::Local => &self.local_data, + StorageType::Local => &self.local_data } } - fn select_data_mut( - &mut self, - storage_type: StorageType, - ) -> &mut HashMap)> { + fn select_data_mut(&mut self, storage_type: StorageType) + -> &mut HashMap)> { match storage_type { StorageType::Session => &mut self.session_data, - StorageType::Local => &mut self.local_data, + StorageType::Local => &mut self.local_data } } fn length(&self, sender: IpcSender, url: ServoUrl, storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - sender - .send(data.get(&origin).map_or(0, |&(_, ref entry)| entry.len())) - .unwrap(); + sender.send(data.get(&origin).map_or(0, |&(_, ref entry)| entry.len())).unwrap(); } - fn key( - &self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - index: u32, - ) { + fn key(&self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + index: u32) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - let key = data - .get(&origin) - .and_then(|&(_, ref entry)| entry.keys().nth(index as usize)) - .cloned(); + let key = data.get(&origin) + .and_then(|&(_, ref entry)| entry.keys().nth(index as usize)) + .cloned(); sender.send(key).unwrap(); } - fn keys(&self, sender: IpcSender>, url: ServoUrl, storage_type: StorageType) { + fn keys(&self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - let keys = data - .get(&origin) - .map_or(vec![], |&(_, ref entry)| entry.keys().cloned().collect()); + let keys = data.get(&origin) + .map_or(vec![], |&(_, ref entry)| entry.keys().cloned().collect()); sender.send(keys).unwrap(); } @@ -155,14 +147,12 @@ impl StorageManager { /// value with the same key name but with different value name /// otherwise sends Err(()) to indicate that the operation would result in /// exceeding the quota limit - fn set_item( - &mut self, - sender: IpcSender), ()>>, - url: ServoUrl, - storage_type: StorageType, - name: String, - value: String, - ) { + fn set_item(&mut self, + sender: IpcSender), ()>>, + url: ServoUrl, + storage_type: StorageType, + name: String, + value: String) { let origin = self.origin_as_string(url); let (this_storage_size, other_storage_size) = { @@ -181,82 +171,64 @@ impl StorageManager { data.insert(origin.clone(), (0, BTreeMap::new())); } - let message = data - .get_mut(&origin) - .map(|&mut (ref mut total, ref mut entry)| { - let mut new_total_size = this_storage_size + value.as_bytes().len(); - if let Some(old_value) = entry.get(&name) { - new_total_size -= old_value.as_bytes().len(); - } else { - new_total_size += name.as_bytes().len(); - } + let message = data.get_mut(&origin).map(|&mut (ref mut total, ref mut entry)| { + let mut new_total_size = this_storage_size + value.as_bytes().len(); + if let Some(old_value) = entry.get(&name) { + new_total_size -= old_value.as_bytes().len(); + } else { + new_total_size += name.as_bytes().len(); + } - if (new_total_size + other_storage_size) > QUOTA_SIZE_LIMIT { - return Err(()); - } + if (new_total_size + other_storage_size) > QUOTA_SIZE_LIMIT { + return Err(()); + } - let message = - entry - .insert(name.clone(), value.clone()) - .map_or(Ok((true, None)), |old| { - if old == value { - Ok((false, None)) - } else { - Ok((true, Some(old))) - } - }); - *total = new_total_size; - message - }) - .unwrap(); + let message = entry.insert(name.clone(), value.clone()).map_or( + Ok((true, None)), + |old| if old == value { + Ok((false, None)) + } else { + Ok((true, Some(old))) + }); + *total = new_total_size; + message + }).unwrap(); sender.send(message).unwrap(); } - fn request_item( - &self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - name: String, - ) { + fn request_item(&self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + name: String) { let origin = self.origin_as_string(url); let data = self.select_data(storage_type); - sender - .send( - data.get(&origin) + sender.send(data.get(&origin) .and_then(|&(_, ref entry)| entry.get(&name)) - .map(String::clone), - ) - .unwrap(); + .map(String::clone)).unwrap(); } /// Sends Some(old_value) in case there was a previous value with the key name, otherwise sends None - fn remove_item( - &mut self, - sender: IpcSender>, - url: ServoUrl, - storage_type: StorageType, - name: String, - ) { + fn remove_item(&mut self, + sender: IpcSender>, + url: ServoUrl, + storage_type: StorageType, + name: String) { let origin = self.origin_as_string(url); let data = self.select_data_mut(storage_type); - let old_value = data - .get_mut(&origin) - .and_then(|&mut (ref mut total, ref mut entry)| { - entry.remove(&name).and_then(|old| { - *total -= name.as_bytes().len() + old.as_bytes().len(); - Some(old) - }) - }); + let old_value = data.get_mut(&origin).and_then(|&mut (ref mut total, ref mut entry)| { + entry.remove(&name).and_then(|old| { + *total -= name.as_bytes().len() + old.as_bytes().len(); + Some(old) + }) + }); sender.send(old_value).unwrap(); } fn clear(&mut self, sender: IpcSender, url: ServoUrl, storage_type: StorageType) { let origin = self.origin_as_string(url); let data = self.select_data_mut(storage_type); - sender - .send( - data.get_mut(&origin) + sender.send(data.get_mut(&origin) .map_or(false, |&mut (ref mut total, ref mut entry)| { if !entry.is_empty() { entry.clear(); @@ -264,10 +236,7 @@ impl StorageManager { true } else { false - } - }), - ) - .unwrap(); + }})).unwrap(); } fn origin_as_string(&self, url: ServoUrl) -> String { diff --git a/components/net/subresource_integrity.rs b/components/net/subresource_integrity.rs index de90fea93389..5088cc114b21 100644 --- a/components/net/subresource_integrity.rs +++ b/components/net/subresource_integrity.rs @@ -4,18 +4,26 @@ use base64; use net_traits::response::{Response, ResponseBody, ResponseType}; -use openssl::hash::{hash, MessageDigest}; +use openssl::hash::{MessageDigest, hash2}; use std::iter::Filter; use std::str::Split; use std::sync::MutexGuard; - -const SUPPORTED_ALGORITHM: &'static [&'static str] = &["sha256", "sha384", "sha512"]; +const SUPPORTED_ALGORITHM: &'static [&'static str] = &[ + "sha256", + "sha384", + "sha512", +]; pub type StaticCharVec = &'static [char]; /// A "space character" according to: /// /// -pub static HTML_SPACE_CHARACTERS: StaticCharVec = - &['\u{0020}', '\u{0009}', '\u{000a}', '\u{000c}', '\u{000d}']; +pub static HTML_SPACE_CHARACTERS: StaticCharVec = &[ + '\u{0020}', + '\u{0009}', + '\u{000a}', + '\u{000c}', + '\u{000d}', +]; #[derive(Clone)] pub struct SriEntry { pub alg: String, @@ -70,18 +78,9 @@ pub fn parsed_metadata(integrity_metadata: &str) -> Vec { } /// -pub fn get_prioritized_hash_function( - hash_func_left: &str, - hash_func_right: &str, -) -> Option { - let left_priority = SUPPORTED_ALGORITHM - .iter() - .position(|s| s.to_owned() == hash_func_left) - .unwrap(); - let right_priority = SUPPORTED_ALGORITHM - .iter() - .position(|s| s.to_owned() == hash_func_right) - .unwrap(); +pub fn get_prioritized_hash_function(hash_func_left: &str, hash_func_right: &str) -> Option { + let left_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_left).unwrap(); + let right_priority = SUPPORTED_ALGORITHM.iter().position(|s| s.to_owned() == hash_func_right).unwrap(); if left_priority == right_priority { return None; @@ -91,6 +90,7 @@ pub fn get_prioritized_hash_function( } else { Some(hash_func_right.to_owned()) } + } /// @@ -99,8 +99,8 @@ pub fn get_strongest_metadata(integrity_metadata_list: Vec) -> Vec) -> Vec -fn apply_algorithm_to_response( - body: MutexGuard, - message_digest: MessageDigest, -) -> String { +fn apply_algorithm_to_response(body: MutexGuard, + message_digest: MessageDigest) + -> String { if let ResponseBody::Done(ref vec) = *body { - let response_digest = hash(message_digest, vec).unwrap(); //Now hash + let response_digest = hash2(message_digest, vec).unwrap(); //Now hash2 base64::encode(&response_digest) } else { unreachable!("Tried to calculate digest of incomplete response body") @@ -171,12 +170,8 @@ pub fn is_response_integrity_valid(integrity_metadata: &str, response: &Response false } -pub fn split_html_space_chars<'a>( - s: &'a str, -) -> Filter, fn(&&str) -> bool> { - fn not_empty(&split: &&str) -> bool { - !split.is_empty() - } - s.split(HTML_SPACE_CHARACTERS) - .filter(not_empty as fn(&&str) -> bool) +pub fn split_html_space_chars<'a>(s: &'a str) -> + Filter, fn(&&str) -> bool> { + fn not_empty(&split: &&str) -> bool { !split.is_empty() } + s.split(HTML_SPACE_CHARACTERS).filter(not_empty as fn(&&str) -> bool) } diff --git a/components/net/tests/cookie.rs b/components/net/tests/cookie.rs index 7190807ed78c..68149736680c 100644 --- a/components/net/tests/cookie.rs +++ b/components/net/tests/cookie.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use cookie_rs; +use hyper::header::{Header, SetCookie}; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net_traits::CookieSource; @@ -88,7 +90,7 @@ fn fn_cookie_constructor() { let cookie = Cookie::new_wrapped(cookie, url, CookieSource::HTTP).unwrap(); assert_eq!(cookie.cookie.value(), "bar"); assert_eq!(cookie.cookie.name(), "baz"); - assert!(cookie.cookie.secure().unwrap_or(false)); + assert!(cookie.cookie.secure()); assert_eq!(&cookie.cookie.path().as_ref().unwrap()[..], "/foo/bar/"); assert_eq!(&cookie.cookie.domain().as_ref().unwrap()[..], "example.com"); assert!(cookie.host_only); @@ -117,13 +119,11 @@ fn test_cookie_secure_prefix() { assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("http://example.com").unwrap(); - let cookie = - cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); + let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); - let cookie = - cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); + let cookie = cookie_rs::Cookie::parse("__Secure-SID=12345; Secure; Domain=example.com").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_some()); } @@ -158,8 +158,7 @@ fn test_cookie_host_prefix() { assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); - let cookie = - cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap(); + let cookie = cookie_rs::Cookie::parse("__Host-SID=12345; Secure; Domain=example.com; Path=/").unwrap(); assert!(Cookie::new_wrapped(cookie, url, CookieSource::HTTP).is_none()); let url = &ServoUrl::parse("https://example.com").unwrap(); @@ -195,18 +194,13 @@ fn test_sort_order() { assert!(b.cookie.path().as_ref().unwrap().len() > a.cookie.path().as_ref().unwrap().len()); assert_eq!(CookieStorage::cookie_comparator(&a, &b), Ordering::Greater); assert_eq!(CookieStorage::cookie_comparator(&b, &a), Ordering::Less); - assert_eq!( - CookieStorage::cookie_comparator(&a, &a_prime), - Ordering::Less - ); - assert_eq!( - CookieStorage::cookie_comparator(&a_prime, &a), - Ordering::Greater - ); + assert_eq!(CookieStorage::cookie_comparator(&a, &a_prime), Ordering::Less); + assert_eq!(CookieStorage::cookie_comparator(&a_prime, &a), Ordering::Greater); assert_eq!(CookieStorage::cookie_comparator(&a, &a), Ordering::Equal); } -fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str) { +fn add_cookie_to_storage(storage: &mut CookieStorage, url: &ServoUrl, cookie_str: &str) +{ let source = CookieSource::HTTP; let cookie = cookie_rs::Cookie::parse(cookie_str.to_owned()).unwrap(); let cookie = Cookie::new_wrapped(cookie, url, source).unwrap(); @@ -232,40 +226,21 @@ fn test_insecure_cookies_cannot_evict_secure_cookie() { let insecure_url = ServoUrl::parse("http://home.example.org:8888/cookie-parser?0001").unwrap(); - add_cookie_to_storage( - &mut storage, - &insecure_url, - "foo=value; Domain=home.example.org", - ); - add_cookie_to_storage( - &mut storage, - &insecure_url, - "foo2=value; Domain=.example.org", - ); + add_cookie_to_storage(&mut storage, &insecure_url, "foo=value; Domain=home.example.org"); + add_cookie_to_storage(&mut storage, &insecure_url, "foo2=value; Domain=.example.org"); add_cookie_to_storage(&mut storage, &insecure_url, "foo3=value; Path=/foo/bar"); add_cookie_to_storage(&mut storage, &insecure_url, "foo4=value; Path=/foo"); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&secure_url, source).unwrap(), - "foo=bar; foo2=bar" - ); + assert_eq!(storage.cookies_for_url(&secure_url, source).unwrap(), "foo=bar; foo2=bar"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo3=bar; foo4=value; foo=bar; foo2=bar" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo=bar; foo2=bar"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo4=bar; foo3=bar; foo4=value; foo=bar; foo2=bar"); } #[test] @@ -293,21 +268,14 @@ fn test_secure_cookies_eviction() { let source = CookieSource::HTTP; assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo3=bar; foo4=value; foo2=value" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), + "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"); } #[test] @@ -335,109 +303,88 @@ fn test_secure_cookies_eviction_non_http_source() { let source = CookieSource::HTTP; assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo2=value"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo3=bar; foo4=value; foo2=value" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), "foo3=bar; foo4=value; foo2=value"); - let url = - ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); + let url = ServoUrl::parse("https://home.example.org:8888/foo/bar/cookie-parser-result?0001").unwrap(); let source = CookieSource::HTTP; - assert_eq!( - storage.cookies_for_url(&url, source).unwrap(), - "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value" - ); + assert_eq!(storage.cookies_for_url(&url, source).unwrap(), + "foo4=bar; foo3=value; foo3=bar; foo4=value; foo2=value"); } -fn add_retrieve_cookies( - set_location: &str, - set_cookies: &[String], - final_location: &str, -) -> String { + +fn add_retrieve_cookies(set_location: &str, + set_cookies: &[String], + final_location: &str) + -> String { let mut storage = CookieStorage::new(5); let url = ServoUrl::parse(set_location).unwrap(); let source = CookieSource::HTTP; // Add all cookies to the store for str_cookie in set_cookies { - let cookie = Cookie::from_cookie_string(str_cookie.to_owned(), &url, source).unwrap(); - storage.push(cookie, &url, source); + let bytes = str_cookie.to_string().into_bytes(); + let header = Header::parse_header(&[bytes]).unwrap(); + let SetCookie(cookies) = header; + for bare_cookie in cookies { + let cookie = Cookie::from_cookie_string(bare_cookie, &url, source).unwrap(); + storage.push(cookie, &url, source); + } } // Get cookies for the test location let url = ServoUrl::parse(final_location).unwrap(); - storage - .cookies_for_url(&url, source) - .unwrap_or("".to_string()) + storage.cookies_for_url(&url, source).unwrap_or("".to_string()) } + #[test] fn test_cookie_eviction_expired() { let mut vec = Vec::new(); for i in 1..6 { - let st = format!( - "extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT", - i - ); + let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2000 21:06:29 GMT", + i); vec.push(st); } vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2027 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies( - "https://home.example.org:8888/cookie-parser?0001", - &vec, - "https://home.example.org:8888/cookie-parser-result?0001", - ); + let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", + &vec, "https://home.example.org:8888/cookie-parser-result?0001"); assert_eq!(&r, "foo=bar"); } + #[test] fn test_cookie_eviction_all_secure_one_nonsecure() { let mut vec = Vec::new(); for i in 1..5 { - let st = format!( - "extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", - i - ); + let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", + i); vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2026 21:06:29 GMT".to_owned()); vec.push("foo2=bar; Secure; expires=Sun, 18-Apr-2028 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies( - "https://home.example.org:8888/cookie-parser?0001", - &vec, - "https://home.example.org:8888/cookie-parser-result?0001", - ); - assert_eq!( - &r, - "extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar" - ); + let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", + &vec, "https://home.example.org:8888/cookie-parser-result?0001"); + assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; foo2=bar"); } + #[test] fn test_cookie_eviction_all_secure_new_nonsecure() { let mut vec = Vec::new(); for i in 1..6 { - let st = format!( - "extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", - i - ); + let st = format!("extra{}=bar; Secure; expires=Sun, 18-Apr-2026 21:06:29 GMT", + i); vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies( - "https://home.example.org:8888/cookie-parser?0001", - &vec, - "https://home.example.org:8888/cookie-parser-result?0001", - ); - assert_eq!( - &r, - "extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar" - ); + let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", + &vec, "https://home.example.org:8888/cookie-parser-result?0001"); + assert_eq!(&r, "extra1=bar; extra2=bar; extra3=bar; extra4=bar; extra5=bar"); } + #[test] fn test_cookie_eviction_all_nonsecure_new_secure() { let mut vec = Vec::new(); @@ -446,17 +393,12 @@ fn test_cookie_eviction_all_nonsecure_new_secure() { vec.push(st); } vec.push("foo=bar; Secure; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies( - "https://home.example.org:8888/cookie-parser?0001", - &vec, - "https://home.example.org:8888/cookie-parser-result?0001", - ); - assert_eq!( - &r, - "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar" - ); + let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", + &vec, "https://home.example.org:8888/cookie-parser-result?0001"); + assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"); } + #[test] fn test_cookie_eviction_all_nonsecure_new_nonsecure() { let mut vec = Vec::new(); @@ -465,13 +407,7 @@ fn test_cookie_eviction_all_nonsecure_new_nonsecure() { vec.push(st); } vec.push("foo=bar; expires=Sun, 18-Apr-2077 21:06:29 GMT".to_owned()); - let r = add_retrieve_cookies( - "https://home.example.org:8888/cookie-parser?0001", - &vec, - "https://home.example.org:8888/cookie-parser-result?0001", - ); - assert_eq!( - &r, - "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar" - ); + let r = add_retrieve_cookies("https://home.example.org:8888/cookie-parser?0001", + &vec, "https://home.example.org:8888/cookie-parser-result?0001"); + assert_eq!(&r, "extra2=bar; extra3=bar; extra4=bar; extra5=bar; foo=bar"); } diff --git a/components/net/tests/cookie_http_state.rs b/components/net/tests/cookie_http_state.rs index ef929277fcba..30cec8b26b2d 100644 --- a/components/net/tests/cookie_http_state.rs +++ b/components/net/tests/cookie_http_state.rs @@ -2,11 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +use hyper::header::{Header, SetCookie}; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net_traits::CookieSource; use servo_url::ServoUrl; + fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String { let mut storage = CookieStorage::new(150); let url = ServoUrl::parse(set_location).unwrap(); @@ -14,17 +16,20 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String // Add all cookies to the store for str_cookie in set_cookies { - if let Some(cookie) = Cookie::from_cookie_string(str_cookie.to_owned().into(), &url, source) - { - storage.push(cookie, &url, source); + let bytes = str_cookie.to_string().into_bytes(); + let header = Header::parse_header(&[bytes]); + if let Ok(SetCookie(cookies)) = header { + for bare_cookie in cookies { + if let Some(cookie) = Cookie::from_cookie_string(bare_cookie, &url, source) { + storage.push(cookie, &url, source); + } + } } } // Get cookies for the test location let url = ServoUrl::parse(final_location).unwrap(); - storage - .cookies_for_url(&url, source) - .unwrap_or("".to_string()) + storage.cookies_for_url(&url, source).unwrap_or("".to_string()) } // Following are all tests extracted from https://github.com/abarth/http-state.git @@ -33,2392 +38,1890 @@ fn run(set_location: &str, set_cookies: &[&str], final_location: &str) -> String #[test] fn test_0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?0001", - &["foo=bar"], - "http://home.example.org:8888/cookie-parser-result?0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?0001", + &["foo=bar"], + "http://home.example.org:8888/cookie-parser-result?0001"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?0002", - &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], - "http://home.example.org:8888/cookie-parser-result?0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?0002", + &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], + "http://home.example.org:8888/cookie-parser-result?0002"); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?0003", - &[ - "foo=bar; Expires=Fri, 07 Aug 2007 08:04:19 GMT", - "foo2=bar2; Expires=Fri, 07 Aug 2017 08:04:19 GMT", - ], - "http://home.example.org:8888/cookie-parser-result?0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?0003", + &["foo=bar; Expires=Fri, 07 Aug 2007 08:04:19 GMT", + "foo2=bar2; Expires=Fri, 07 Aug 2017 08:04:19 GMT"], + "http://home.example.org:8888/cookie-parser-result?0003"); assert_eq!(&r, "foo2=bar2"); } #[test] fn test_0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?0004", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?0004", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0004"); assert_eq!(&r, ""); } #[test] fn test_0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?0005", - &["foo=bar; max-age=10000;"], - "http://home.example.org:8888/cookie-parser-result?0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?0005", + &["foo=bar; max-age=10000;"], + "http://home.example.org:8888/cookie-parser-result?0005"); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?0006", - &["foo=bar; max-age=0;"], - "http://home.example.org:8888/cookie-parser-result?0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?0006", + &["foo=bar; max-age=0;"], + "http://home.example.org:8888/cookie-parser-result?0006"); assert_eq!(&r, ""); } #[test] fn test_0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?0007", - &["foo=bar; version=1;"], - "http://home.example.org:8888/cookie-parser-result?0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?0007", + &["foo=bar; version=1;"], + "http://home.example.org:8888/cookie-parser-result?0007"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?0008", - &["foo=bar; version=1000;"], - "http://home.example.org:8888/cookie-parser-result?0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?0008", + &["foo=bar; version=1000;"], + "http://home.example.org:8888/cookie-parser-result?0008"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?0009", - &["foo=bar; customvalue=1000;"], - "http://home.example.org:8888/cookie-parser-result?0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?0009", + &["foo=bar; customvalue=1000;"], + "http://home.example.org:8888/cookie-parser-result?0009"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?0010", - &["foo=bar; secure;"], - "http://home.example.org:8888/cookie-parser-result?0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?0010", + &["foo=bar; secure;"], + "http://home.example.org:8888/cookie-parser-result?0010"); assert_eq!(&r, ""); } #[test] fn test_0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?0011", - &["foo=bar; customvalue=\"1000 or more\";"], - "http://home.example.org:8888/cookie-parser-result?0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?0011", + &["foo=bar; customvalue=\"1000 or more\";"], + "http://home.example.org:8888/cookie-parser-result?0011"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?0012", - &["foo=bar; customvalue=\"no trailing semicolon\""], - "http://home.example.org:8888/cookie-parser-result?0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?0012", + &["foo=bar; customvalue=\"no trailing semicolon\""], + "http://home.example.org:8888/cookie-parser-result?0012"); assert_eq!(&r, "foo=bar"); } #[test] fn test_0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?0013", - &["foo=bar", "foo=qux"], - "http://home.example.org:8888/cookie-parser-result?0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?0013", + &["foo=bar", "foo=qux"], + "http://home.example.org:8888/cookie-parser-result?0013"); assert_eq!(&r, "foo=qux"); } #[test] fn test_0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?0014", - &["foo1=bar", "foo2=qux"], - "http://home.example.org:8888/cookie-parser-result?0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?0014", + &["foo1=bar", "foo2=qux"], + "http://home.example.org:8888/cookie-parser-result?0014"); assert_eq!(&r, "foo1=bar; foo2=qux"); } #[test] fn test_0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?0015", - &["a=b", "z=y"], - "http://home.example.org:8888/cookie-parser-result?0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?0015", + &["a=b", "z=y"], + "http://home.example.org:8888/cookie-parser-result?0015"); assert_eq!(&r, "a=b; z=y"); } #[test] fn test_0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?0016", - &["z=y", "a=b"], - "http://home.example.org:8888/cookie-parser-result?0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?0016", + &["z=y", "a=b"], + "http://home.example.org:8888/cookie-parser-result?0016"); assert_eq!(&r, "z=y; a=b"); } #[test] fn test_0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?0017", - &["z=y, a=b"], - "http://home.example.org:8888/cookie-parser-result?0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?0017", + &["z=y, a=b"], + "http://home.example.org:8888/cookie-parser-result?0017"); assert_eq!(&r, "z=y, a=b"); } #[test] fn test_0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?0018", - &["z=y; foo=bar, a=b"], - "http://home.example.org:8888/cookie-parser-result?0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?0018", + &["z=y; foo=bar, a=b"], + "http://home.example.org:8888/cookie-parser-result?0018"); assert_eq!(&r, "z=y"); } #[test] fn test_0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?0019", - &["foo=b;max-age=3600, c=d;path=/"], - "http://home.example.org:8888/cookie-parser-result?0019", - ); + let r = run("http://home.example.org:8888/cookie-parser?0019", + &["foo=b;max-age=3600, c=d;path=/"], + "http://home.example.org:8888/cookie-parser-result?0019"); assert_eq!(&r, "foo=b"); } #[test] fn test_0020() { - let r = run( - "http://home.example.org:8888/cookie-parser?0020", - &["a=b", "=", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0020", - ); + let r = run("http://home.example.org:8888/cookie-parser?0020", + &["a=b", "=", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0020"); assert_eq!(&r, "a=b; c=d"); } #[test] fn test_0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?0021", - &["a=b", "=x", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?0021", + &["a=b", "=x", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0021"); assert_eq!(&r, "a=b; c=d"); } #[test] fn test_0022() { - let r = run( - "http://home.example.org:8888/cookie-parser?0022", - &["a=b", "x=", "c=d"], - "http://home.example.org:8888/cookie-parser-result?0022", - ); + let r = run("http://home.example.org:8888/cookie-parser?0022", + &["a=b", "x=", "c=d"], + "http://home.example.org:8888/cookie-parser-result?0022"); assert_eq!(&r, "a=b; x=; c=d"); } #[test] fn test_0023() { - let r = run( - "http://home.example.org:8888/cookie-parser?0023", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0023", - ); + let r = run("http://home.example.org:8888/cookie-parser?0023", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0023"); assert_eq!(&r, ""); } #[test] fn test_0024() { - let r = run( - "http://home.example.org:8888/cookie-parser?0024", - &["foo", "="], - "http://home.example.org:8888/cookie-parser-result?0024", - ); + let r = run("http://home.example.org:8888/cookie-parser?0024", + &["foo", "="], + "http://home.example.org:8888/cookie-parser-result?0024"); assert_eq!(&r, ""); } #[test] fn test_0025() { - let r = run( - "http://home.example.org:8888/cookie-parser?0025", - &["foo", "; bar"], - "http://home.example.org:8888/cookie-parser-result?0025", - ); + let r = run("http://home.example.org:8888/cookie-parser?0025", + &["foo", "; bar"], + "http://home.example.org:8888/cookie-parser-result?0025"); assert_eq!(&r, ""); } #[test] fn test_0026() { - let r = run( - "http://home.example.org:8888/cookie-parser?0026", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0026", - ); + let r = run("http://home.example.org:8888/cookie-parser?0026", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0026"); assert_eq!(&r, ""); } #[test] fn test_0027() { - let r = run( - "http://home.example.org:8888/cookie-parser?0027", - &["foo", "bar"], - "http://home.example.org:8888/cookie-parser-result?0027", - ); + let r = run("http://home.example.org:8888/cookie-parser?0027", + &["foo", "bar"], + "http://home.example.org:8888/cookie-parser-result?0027"); assert_eq!(&r, ""); } #[test] fn test_0028() { - let r = run( - "http://home.example.org:8888/cookie-parser?0028", - &["foo"], - "http://home.example.org:8888/cookie-parser-result?0028", - ); + let r = run("http://home.example.org:8888/cookie-parser?0028", + &["foo"], + "http://home.example.org:8888/cookie-parser-result?0028"); assert_eq!(&r, ""); } #[test] fn test_attribute0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0001", - &["foo=bar; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0001", + &["foo=bar; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0001"); assert_eq!(&r, ""); } #[test] fn test_attribute0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0002", - &["foo=bar; seCURe"], - "http://home.example.org:8888/cookie-parser-result?attribute0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0002", + &["foo=bar; seCURe"], + "http://home.example.org:8888/cookie-parser-result?attribute0002"); assert_eq!(&r, ""); } #[test] fn test_attribute0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0003", - &["foo=bar; \"Secure\""], - "http://home.example.org:8888/cookie-parser-result?attribute0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0003", + &["foo=bar; \"Secure\""], + "http://home.example.org:8888/cookie-parser-result?attribute0003"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0004", - &["foo=bar; Secure="], - "http://home.example.org:8888/cookie-parser-result?attribute0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0004", + &["foo=bar; Secure="], + "http://home.example.org:8888/cookie-parser-result?attribute0004"); assert_eq!(&r, ""); } #[test] fn test_attribute0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0005", - &["foo=bar; Secure=aaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0005", + &["foo=bar; Secure=aaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0005"); assert_eq!(&r, ""); } #[test] fn test_attribute0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0006", - &["foo=bar; Secure qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0006", + &["foo=bar; Secure qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0006"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0007", - &["foo=bar; Secure =aaaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0007", + &["foo=bar; Secure =aaaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0007"); assert_eq!(&r, ""); } #[test] fn test_attribute0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0008", - &["foo=bar; Secure= aaaaa"], - "http://home.example.org:8888/cookie-parser-result?attribute0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0008", + &["foo=bar; Secure= aaaaa"], + "http://home.example.org:8888/cookie-parser-result?attribute0008"); assert_eq!(&r, ""); } #[test] fn test_attribute0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0009", - &["foo=bar; Secure; qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0009", + &["foo=bar; Secure; qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0009"); assert_eq!(&r, ""); } #[test] fn test_attribute0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0010", - &["foo=bar; Secure;qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0010", + &["foo=bar; Secure;qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0010"); assert_eq!(&r, ""); } #[test] fn test_attribute0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0011", - &["foo=bar; Secure ; qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0011", + &["foo=bar; Secure ; qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0011"); assert_eq!(&r, ""); } #[test] fn test_attribute0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0012", - &["foo=bar; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0012", + &["foo=bar; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0012"); assert_eq!(&r, ""); } #[test] fn test_attribute0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0013", - &["foo=bar; Secure ;"], - "http://home.example.org:8888/cookie-parser-result?attribute0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0013", + &["foo=bar; Secure ;"], + "http://home.example.org:8888/cookie-parser-result?attribute0013"); assert_eq!(&r, ""); } #[test] fn test_attribute0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0014", - &["foo=bar; Path"], - "http://home.example.org:8888/cookie-parser-result?attribute0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0014", + &["foo=bar; Path"], + "http://home.example.org:8888/cookie-parser-result?attribute0014"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0015", - &["foo=bar; Path="], - "http://home.example.org:8888/cookie-parser-result?attribute0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0015", + &["foo=bar; Path="], + "http://home.example.org:8888/cookie-parser-result?attribute0015"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0016", - &["foo=bar; Path=/"], - "http://home.example.org:8888/cookie-parser-result?attribute0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0016", + &["foo=bar; Path=/"], + "http://home.example.org:8888/cookie-parser-result?attribute0016"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0017", - &["foo=bar; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0017", + &["foo=bar; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0017"); assert_eq!(&r, ""); } #[test] fn test_attribute0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0018", - &["foo=bar; Path =/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0018", + &["foo=bar; Path =/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0018"); assert_eq!(&r, ""); } #[test] fn test_attribute0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0019", - &["foo=bar; Path= /qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0019", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0019", + &["foo=bar; Path= /qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0019"); assert_eq!(&r, ""); } #[test] fn test_attribute0020() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0020", - &["foo=bar; Path=/qux ; taz"], - "http://home.example.org:8888/cookie-parser-result?attribute0020", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0020", + &["foo=bar; Path=/qux ; taz"], + "http://home.example.org:8888/cookie-parser-result?attribute0020"); assert_eq!(&r, ""); } #[test] fn test_attribute0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0021", - &["foo=bar; Path=/qux; Path=/"], - "http://home.example.org:8888/cookie-parser-result?attribute0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0021", + &["foo=bar; Path=/qux; Path=/"], + "http://home.example.org:8888/cookie-parser-result?attribute0021"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0022() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0022", - &["foo=bar; Path=/; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0022", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0022", + &["foo=bar; Path=/; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0022"); assert_eq!(&r, ""); } #[test] fn test_attribute0023() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0023", - &["foo=bar; Path=/qux; Path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?attribute0023", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0023", + &["foo=bar; Path=/qux; Path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?attribute0023"); assert_eq!(&r, "foo=bar"); } #[test] fn test_attribute0024() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0024", - &["foo=bar; Path=/cookie-parser-result; Path=/qux"], - "http://home.example.org:8888/cookie-parser-result?attribute0024", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0024", + &["foo=bar; Path=/cookie-parser-result; Path=/qux"], + "http://home.example.org:8888/cookie-parser-result?attribute0024"); assert_eq!(&r, ""); } #[test] fn test_attribute0025() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0025", - &["foo=bar; qux; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0025", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0025", + &["foo=bar; qux; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0025"); assert_eq!(&r, ""); } #[test] fn test_attribute0026() { - let r = run( - "http://home.example.org:8888/cookie-parser?attribute0026", - &["foo=bar; qux=\"aaa;bbb\"; Secure"], - "http://home.example.org:8888/cookie-parser-result?attribute0026", - ); + let r = run("http://home.example.org:8888/cookie-parser?attribute0026", + &["foo=bar; qux=\"aaa;bbb\"; Secure"], + "http://home.example.org:8888/cookie-parser-result?attribute0026"); assert_eq!(&r, ""); } #[test] fn test_charset0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?charset0001", - &[ - "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}", - ], - "http://home.example.org:8888/cookie-parser-result?charset0001", - ); - assert_eq!( - &r, - "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}" - ); + let r = run("http://home.example.org:8888/cookie-parser?charset0001", + &["foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}"], + "http://home.example.org:8888/cookie-parser-result?charset0001"); + assert_eq!(&r, "foo=\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}"); } #[test] fn test_charset0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?charset0002", - &[ - "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}", - ], - "http://home.example.org:8888/cookie-parser-result?charset0002", - ); - assert_eq!( - &r, - "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}" - ); + let r = run("http://home.example.org:8888/cookie-parser?charset0002", + &["\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}"], + "http://home.example.org:8888/cookie-parser-result?charset0002"); + assert_eq!(&r, "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}"); } #[test] fn test_charset0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?charset0003", - &[ - "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}; \u{5b8c}\ - \u{5168}\u{624b}\u{518c}", - ], - "http://home.example.org:8888/cookie-parser-result?charset0003", - ); - assert_eq!( - &r, - "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}" - ); + let r = run("http://home.example.org:8888/cookie-parser?charset0003", + &["\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}; \u{5b8c}\ +\u{5168}\u{624b}\u{518c}"], + "http://home.example.org:8888/cookie-parser-result?charset0003"); + assert_eq!(&r, "\u{6625}\u{8282}\u{56de}=\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}"); } #[test] fn test_charset0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?charset0004", - &[ - "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}\"", - ], - "http://home.example.org:8888/cookie-parser-result?charset0004", - ); - assert_eq!( - &r, - "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ - \u{5168}\u{624b}\u{518c}\"" - ); + let r = run("http://home.example.org:8888/cookie-parser?charset0004", + &["foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}\""], + "http://home.example.org:8888/cookie-parser-result?charset0004"); + assert_eq!(&r, "foo=\"\u{6625}\u{8282}\u{56de}\u{5bb6}\u{8def}\u{b7}\u{6625}\u{8fd0}\u{5b8c}\ +\u{5168}\u{624b}\u{518c}\""); } #[test] fn test_chromium0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0001", - &["a=b"], - "http://home.example.org:8888/cookie-parser-result?chromium0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0001", + &["a=b"], + "http://home.example.org:8888/cookie-parser-result?chromium0001"); assert_eq!(&r, "a=b"); } #[test] fn test_chromium0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0002", - &["aBc=\"zzz \" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0002", + &["aBc=\"zzz \" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0002"); assert_eq!(&r, "aBc=\"zzz \""); } #[test] fn test_chromium0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0003", - &["aBc=\"zzz \" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0003", + &["aBc=\"zzz \" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0003"); assert_eq!(&r, "aBc=\"zzz \""); } #[test] fn test_chromium0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0004", - &["aBc=\"zz;pp\" ; ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0004", + &["aBc=\"zz;pp\" ; ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0004"); assert_eq!(&r, "aBc=\"zz"); } #[test] fn test_chromium0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0005", - &["aBc=\"zz ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0005", + &["aBc=\"zz ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0005"); assert_eq!(&r, "aBc=\"zz"); } #[test] fn test_chromium0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0006", - &["aBc=\"zzz \" \"ppp\" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0006", + &["aBc=\"zzz \" \"ppp\" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0006"); assert_eq!(&r, "aBc=\"zzz \" \"ppp\""); } #[test] fn test_chromium0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0007", - &["aBc=\"zzz \" \"ppp\" ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0007", + &["aBc=\"zzz \" \"ppp\" ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0007"); assert_eq!(&r, "aBc=\"zzz \" \"ppp\""); } #[test] fn test_chromium0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0008", - &["aBc=A\"B ;"], - "http://home.example.org:8888/cookie-parser-result?chromium0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0008", + &["aBc=A\"B ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0008"); assert_eq!(&r, "aBc=A\"B"); } #[test] fn test_chromium0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0009", - &["BLAHHH; path=/;"], - "http://home.example.org:8888/cookie-parser-result?chromium0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0009", + &["BLAHHH; path=/;"], + "http://home.example.org:8888/cookie-parser-result?chromium0009"); assert_eq!(&r, ""); } #[test] fn test_chromium0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0010", - &["\"BLA\\\"HHH\"; path=/;"], - "http://home.example.org:8888/cookie-parser-result?chromium0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0010", + &["\"BLA\\\"HHH\"; path=/;"], + "http://home.example.org:8888/cookie-parser-result?chromium0010"); assert_eq!(&r, ""); } #[test] fn test_chromium0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0011", - &["a=\"B"], - "http://home.example.org:8888/cookie-parser-result?chromium0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0011", + &["a=\"B"], + "http://home.example.org:8888/cookie-parser-result?chromium0011"); assert_eq!(&r, "a=\"B"); } #[test] fn test_chromium0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0012", - &["=ABC"], - "http://home.example.org:8888/cookie-parser-result?chromium0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0012", + &["=ABC"], + "http://home.example.org:8888/cookie-parser-result?chromium0012"); assert_eq!(&r, ""); } #[test] fn test_chromium0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0013", - &["ABC=; path = /"], - "http://home.example.org:8888/cookie-parser-result?chromium0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0013", + &["ABC=; path = /"], + "http://home.example.org:8888/cookie-parser-result?chromium0013"); assert_eq!(&r, "ABC="); } #[test] fn test_chromium0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0014", - &[" A = BC ;foo;;; bar"], - "http://home.example.org:8888/cookie-parser-result?chromium0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0014", + &[" A = BC ;foo;;; bar"], + "http://home.example.org:8888/cookie-parser-result?chromium0014"); assert_eq!(&r, "A=BC"); } #[test] fn test_chromium0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0015", - &[" A=== BC ;foo;;; bar"], - "http://home.example.org:8888/cookie-parser-result?chromium0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0015", + &[" A=== BC ;foo;;; bar"], + "http://home.example.org:8888/cookie-parser-result?chromium0015"); assert_eq!(&r, "A=== BC"); } #[test] fn test_chromium0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0016", - &[ - "foo=\"zohNumRKgI0oxyhSsV3Z7D\" ; expires=Sun, 18-Apr-2027 21:06:29 GMT\ - ; path=/ ;", - ], - "http://home.example.org:8888/cookie-parser-result?chromium0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0016", + &["foo=\"zohNumRKgI0oxyhSsV3Z7D\" ; expires=Sun, 18-Apr-2027 21:06:29 GMT\ + ; path=/ ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0016"); assert_eq!(&r, "foo=\"zohNumRKgI0oxyhSsV3Z7D\""); } #[test] fn test_chromium0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0017", - &[ - "foo=zohNumRKgI0oxyhSsV3Z7D ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; p\ - ath=/ ;", - ], - "http://home.example.org:8888/cookie-parser-result?chromium0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0017", + &["foo=zohNumRKgI0oxyhSsV3Z7D ; expires=Sun, 18-Apr-2027 21:06:29 GMT ; p\ +ath=/ ;"], + "http://home.example.org:8888/cookie-parser-result?chromium0017"); assert_eq!(&r, "foo=zohNumRKgI0oxyhSsV3Z7D"); } #[test] fn test_chromium0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0018", - &[], - "http://home.example.org:8888/cookie-parser-result?chromium0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0018", + &[], + "http://home.example.org:8888/cookie-parser-result?chromium0018"); assert_eq!(&r, ""); } #[test] fn test_chromium0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0019", - &[ - "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - ], - "http://home.example.org:8888/cookie-parser-result?chromium0019", - ); - assert_eq!( - &r, - "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ - aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0019", + &["a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"], + "http://home.example.org:8888/cookie-parser-result?chromium0019"); + assert_eq!(&r, "a=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\ +aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } #[test] fn test_chromium0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?chromium0021", - &[], - "http://home.example.org:8888/cookie-parser-result?chromium0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?chromium0021", + &[], + "http://home.example.org:8888/cookie-parser-result?chromium0021"); assert_eq!(&r, ""); } #[test] fn test_comma0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0001", - &["foo=bar, baz=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0001", + &["foo=bar, baz=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0001"); assert_eq!(&r, "foo=bar, baz=qux"); } #[test] fn test_comma0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0002", - &["foo=\"bar, baz=qux\""], - "http://home.example.org:8888/cookie-parser-result?comma0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0002", + &["foo=\"bar, baz=qux\""], + "http://home.example.org:8888/cookie-parser-result?comma0002"); assert_eq!(&r, "foo=\"bar, baz=qux\""); } #[test] fn test_comma0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0003", - &["foo=bar; b,az=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0003", + &["foo=bar; b,az=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0003"); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0004", - &["foo=bar; baz=q,ux"], - "http://home.example.org:8888/cookie-parser-result?comma0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0004", + &["foo=bar; baz=q,ux"], + "http://home.example.org:8888/cookie-parser-result?comma0004"); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0005", - &["foo=bar; Max-Age=50,399"], - "http://home.example.org:8888/cookie-parser-result?comma0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0005", + &["foo=bar; Max-Age=50,399"], + "http://home.example.org:8888/cookie-parser-result?comma0005"); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0006", - &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], - "http://home.example.org:8888/cookie-parser-result?comma0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0006", + &["foo=bar; Expires=Fri, 07 Aug 2019 08:04:19 GMT"], + "http://home.example.org:8888/cookie-parser-result?comma0006"); assert_eq!(&r, "foo=bar"); } #[test] fn test_comma0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?comma0007", - &["foo=bar; Expires=Fri 07 Aug 2019 08:04:19 GMT, baz=qux"], - "http://home.example.org:8888/cookie-parser-result?comma0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?comma0007", + &["foo=bar; Expires=Fri 07 Aug 2019 08:04:19 GMT, baz=qux"], + "http://home.example.org:8888/cookie-parser-result?comma0007"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0001", - &["foo=bar; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0001", + &["foo=bar; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0001"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0002", - &["foo=bar; domain=home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0002", + &["foo=bar; domain=home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0002"); assert_eq!(&r, ""); } #[test] fn test_domain0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0003", - &["foo=bar; domain=.home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0003", + &["foo=bar; domain=.home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0003"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0004", - &["foo=bar; domain=home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0004", + &["foo=bar; domain=home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0004"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0005", - &["foo=bar; domain=.home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0005", + &["foo=bar; domain=.home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0005"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0006", - &["foo=bar; domain=.home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0006", + &["foo=bar; domain=.home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0006"); assert_eq!(&r, ""); } #[test] fn test_domain0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0007", - &["foo=bar; domain=sibling.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0007", + &["foo=bar; domain=sibling.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0007"); assert_eq!(&r, ""); } #[test] fn test_domain0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0008", - &["foo=bar; domain=.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0008", + &["foo=bar; domain=.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0008"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0009", - &["foo=bar; domain=example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0009", + &["foo=bar; domain=example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0009"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0010", - &["foo=bar; domain=..home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0010", + &["foo=bar; domain=..home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0010"); assert_eq!(&r, ""); } #[test] fn test_domain0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0011", - &["foo=bar; domain=home..example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0011", + &["foo=bar; domain=home..example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0011"); assert_eq!(&r, ""); } #[test] fn test_domain0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0012", - &["foo=bar; domain= .home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0012", + &["foo=bar; domain= .home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0012"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0013", - &["foo=bar; domain= . home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0013", + &["foo=bar; domain= . home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0013"); assert_eq!(&r, ""); } #[test] fn test_domain0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0014", - &["foo=bar; domain=home.example.org."], - "http://home.example.org:8888/cookie-parser-result?domain0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0014", + &["foo=bar; domain=home.example.org."], + "http://home.example.org:8888/cookie-parser-result?domain0014"); assert_eq!(&r, ""); } #[test] fn test_domain0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0015", - &["foo=bar; domain=home.example.org.."], - "http://home.example.org:8888/cookie-parser-result?domain0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0015", + &["foo=bar; domain=home.example.org.."], + "http://home.example.org:8888/cookie-parser-result?domain0015"); assert_eq!(&r, ""); } #[test] fn test_domain0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0016", - &["foo=bar; domain=home.example.org ."], - "http://home.example.org:8888/cookie-parser-result?domain0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0016", + &["foo=bar; domain=home.example.org ."], + "http://home.example.org:8888/cookie-parser-result?domain0016"); assert_eq!(&r, ""); } #[test] fn test_domain0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0017", - &["foo=bar; domain=.org"], - "http://home.example.org:8888/cookie-parser-result?domain0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0017", + &["foo=bar; domain=.org"], + "http://home.example.org:8888/cookie-parser-result?domain0017"); assert_eq!(&r, ""); } #[test] fn test_domain0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0018", - &["foo=bar; domain=.org."], - "http://home.example.org:8888/cookie-parser-result?domain0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0018", + &["foo=bar; domain=.org."], + "http://home.example.org:8888/cookie-parser-result?domain0018"); assert_eq!(&r, ""); } #[test] fn test_domain0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0019", - &[ - "foo=bar; domain=home.example.org", - "foo2=bar2; domain=.home.example.org", - ], - "http://home.example.org:8888/cookie-parser-result?domain0019", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0019", + &["foo=bar; domain=home.example.org", "foo2=bar2; domain=.home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0019"); assert_eq!(&r, "foo=bar; foo2=bar2"); } #[test] fn test_domain0020() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0020", - &[ - "foo2=bar2; domain=.home.example.org", - "foo=bar; domain=home.example.org", - ], - "http://home.example.org:8888/cookie-parser-result?domain0020", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0020", + &["foo2=bar2; domain=.home.example.org", "foo=bar; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0020"); assert_eq!(&r, "foo2=bar2; foo=bar"); } #[test] fn test_domain0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0021", - &["foo=bar; domain=\"home.example.org\""], - "http://home.example.org:8888/cookie-parser-result?domain0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0021", + &["foo=bar; domain=\"home.example.org\""], + "http://home.example.org:8888/cookie-parser-result?domain0021"); assert_eq!(&r, ""); } #[test] fn test_domain0022() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0022", - &[ - "foo=bar; domain=home.example.org", - "foo2=bar2; domain=.example.org", - ], - "http://home.example.org:8888/cookie-parser-result?domain0022", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0022", + &["foo=bar; domain=home.example.org", "foo2=bar2; domain=.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0022"); assert_eq!(&r, "foo=bar; foo2=bar2"); } #[test] fn test_domain0023() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0023", - &[ - "foo2=bar2; domain=.example.org", - "foo=bar; domain=home.example.org", - ], - "http://home.example.org:8888/cookie-parser-result?domain0023", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0023", + &["foo2=bar2; domain=.example.org", "foo=bar; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0023"); assert_eq!(&r, "foo2=bar2; foo=bar"); } #[test] fn test_domain0024() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0024", - &["foo=bar; domain=.example.org; domain=home.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0024", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0024", + &["foo=bar; domain=.example.org; domain=home.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0024"); assert_eq!(&r, ""); } #[test] fn test_domain0025() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0025", - &["foo=bar; domain=home.example.org; domain=.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0025", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0025", + &["foo=bar; domain=home.example.org; domain=.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0025"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0026() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0026", - &["foo=bar; domain=home.eXaMpLe.org"], - "http://home.example.org:8888/cookie-parser-result?domain0026", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0026", + &["foo=bar; domain=home.eXaMpLe.org"], + "http://home.example.org:8888/cookie-parser-result?domain0026"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0027() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0027", - &["foo=bar; domain=home.example.org:8888"], - "http://home.example.org:8888/cookie-parser-result?domain0027", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0027", + &["foo=bar; domain=home.example.org:8888"], + "http://home.example.org:8888/cookie-parser-result?domain0027"); assert_eq!(&r, ""); } #[test] fn test_domain0028() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0028", - &["foo=bar; domain=subdomain.home.example.org"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0028", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0028", + &["foo=bar; domain=subdomain.home.example.org"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0028"); assert_eq!(&r, ""); } #[test] fn test_domain0029() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0029", - &["foo=bar"], - "http://subdomain.home.example.org:8888/cookie-parser-result?domain0029", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0029", + &["foo=bar"], + "http://subdomain.home.example.org:8888/cookie-parser-result?domain0029"); assert_eq!(&r, ""); } #[test] fn test_domain0031() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0031", - &["foo=bar; domain=home.example.org; domain=.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0031", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0031", + &["foo=bar; domain=home.example.org; domain=.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0031"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0033() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0033", - &["foo=bar; domain=home.example.org"], - "http://hoMe.eXaMplE.org:8888/cookie-parser-result?domain0033", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0033", + &["foo=bar; domain=home.example.org"], + "http://hoMe.eXaMplE.org:8888/cookie-parser-result?domain0033"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0034() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0034", - &["foo=bar; domain=home.example.org; domain=home.example.com"], - "http://home.example.org:8888/cookie-parser-result?domain0034", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0034", + &["foo=bar; domain=home.example.org; domain=home.example.com"], + "http://home.example.org:8888/cookie-parser-result?domain0034"); assert_eq!(&r, ""); } #[test] fn test_domain0035() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0035", - &["foo=bar; domain=home.example.com; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0035", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0035", + &["foo=bar; domain=home.example.com; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0035"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0036() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0036", - &[ - "foo=bar; domain=home.example.org; domain=home.example.com; domain=home.\ - example.org", - ], - "http://home.example.org:8888/cookie-parser-result?domain0036", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0036", + &["foo=bar; domain=home.example.org; domain=home.example.com; domain=home.\ +example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0036"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0037() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0037", - &[ - "foo=bar; domain=home.example.com; domain=home.example.org; domain=home.\ - example.com", - ], - "http://home.example.org:8888/cookie-parser-result?domain0037", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0037", + &["foo=bar; domain=home.example.com; domain=home.example.org; domain=home.\ +example.com"], + "http://home.example.org:8888/cookie-parser-result?domain0037"); assert_eq!(&r, ""); } #[test] fn test_domain0038() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0038", - &["foo=bar; domain=home.example.org; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0038", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0038", + &["foo=bar; domain=home.example.org; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0038"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0039() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0039", - &["foo=bar; domain=home.example.org; domain=example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0039", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0039", + &["foo=bar; domain=home.example.org; domain=example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0039"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0040() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0040", - &["foo=bar; domain=example.org; domain=home.example.org"], - "http://home.example.org:8888/cookie-parser-result?domain0040", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0040", + &["foo=bar; domain=example.org; domain=home.example.org"], + "http://home.example.org:8888/cookie-parser-result?domain0040"); assert_eq!(&r, "foo=bar"); } #[test] fn test_domain0041() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0041", - &["foo=bar; domain=.sibling.example.org"], - "http://sibling.example.org:8888/cookie-parser-result?domain0041", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0041", + &["foo=bar; domain=.sibling.example.org"], + "http://sibling.example.org:8888/cookie-parser-result?domain0041"); assert_eq!(&r, ""); } #[test] fn test_domain0042() { - let r = run( - "http://home.example.org:8888/cookie-parser?domain0042", - &["foo=bar; domain=.sibling.home.example.org"], - "http://sibling.home.example.org:8888/cookie-parser-result?domain0042", - ); + let r = run("http://home.example.org:8888/cookie-parser?domain0042", + &["foo=bar; domain=.sibling.home.example.org"], + "http://sibling.home.example.org:8888/cookie-parser-result?domain0042"); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0001", - &["foo=bar; max-age=-1"], - "http://home.example.org:8888/cookie-parser-result?mozilla0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0001", + &["foo=bar; max-age=-1"], + "http://home.example.org:8888/cookie-parser-result?mozilla0001"); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0002", - &["foo=bar; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0002", + &["foo=bar; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0002"); assert_eq!(&r, ""); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0003", - &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], - "http://home.example.org:8888/cookie-parser-result?mozilla0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0003", + &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], + "http://home.example.org:8888/cookie-parser-result?mozilla0003"); assert_eq!(&r, ""); } #[test] fn test_mozilla0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0004", - &["foo=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0004", + &["foo=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0004"); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0005", - &["foo=bar; max-age=-20"], - "http://home.example.org:8888/cookie-parser-result?mozilla0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0005", + &["foo=bar; max-age=-20"], + "http://home.example.org:8888/cookie-parser-result?mozilla0005"); assert_eq!(&r, ""); } #[test] fn test_mozilla0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0006", - &["foo=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0006", + &["foo=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0006"); assert_eq!(&r, "foo=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0007", - &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], - "http://home.example.org:8888/cookie-parser-result?mozilla0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0007", + &["foo=bar; expires=Thu, 10 Apr 1980 16:33:12 GMT"], + "http://home.example.org:8888/cookie-parser-result?mozilla0007"); assert_eq!(&r, ""); } #[test] fn test_mozilla0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0008", - &["foo=bar; max-age=60", "foo1=bar; max-age=60"], - "http://home.example.org:8888/cookie-parser-result?mozilla0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0008", + &["foo=bar; max-age=60", "foo1=bar; max-age=60"], + "http://home.example.org:8888/cookie-parser-result?mozilla0008"); assert_eq!(&r, "foo=bar; foo1=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0009", - &[ - "foo=bar; max-age=60", - "foo1=bar; max-age=60", - "foo=differentvalue; max-age=0", - ], - "http://home.example.org:8888/cookie-parser-result?mozilla0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0009", + &["foo=bar; max-age=60", "foo1=bar; max-age=60", "foo=differentvalue; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0009"); assert_eq!(&r, "foo1=bar"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0010", - &[ - "foo=bar; max-age=60", - "foo1=bar; max-age=60", - "foo=differentvalue; max-age=0", - "foo2=evendifferentvalue; max-age=0", - ], - "http://home.example.org:8888/cookie-parser-result?mozilla0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0010", + &["foo=bar; max-age=60", + "foo1=bar; max-age=60", + "foo=differentvalue; max-age=0", + "foo2=evendifferentvalue; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0010"); assert_eq!(&r, "foo1=bar"); } #[test] fn test_mozilla0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0011", - &[ - "test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! ma\ - x-age=20;=;;", - ], - "http://home.example.org:8888/cookie-parser-result?mozilla0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0011", + &["test=parser; domain=.parser.test; ;; ;=; ,,, ===,abc,=; abracadabra! ma\ +x-age=20;=;;"], + "http://home.example.org:8888/cookie-parser-result?mozilla0011"); assert_eq!(&r, ""); } #[test] fn test_mozilla0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0012", - &[ - "test=\"fubar! = foo;bar\\\";\" parser; max-age=6", - "five; max-age=2.63,", - ], - "http://home.example.org:8888/cookie-parser-result?mozilla0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0012", + &["test=\"fubar! = foo;bar\\\";\" parser; max-age=6", "five; max-age=2.63,"], + "http://home.example.org:8888/cookie-parser-result?mozilla0012"); assert_eq!(&r, "test=\"fubar! = foo"); } #[test] #[should_panic] // Look at cookie_http_state_utils.py if this test fails fn test_mozilla0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0013", - &["test=kill; max-age=0", "five; max-age=0"], - "http://home.example.org:8888/cookie-parser-result?mozilla0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0013", + &["test=kill; max-age=0", "five; max-age=0"], + "http://home.example.org:8888/cookie-parser-result?mozilla0013"); assert_eq!(&r, ""); } #[test] fn test_mozilla0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0014", - &["six"], - "http://home.example.org:8888/cookie-parser-result?mozilla0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0014", + &["six"], + "http://home.example.org:8888/cookie-parser-result?mozilla0014"); assert_eq!(&r, ""); } #[test] fn test_mozilla0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0015", - &["six", "seven"], - "http://home.example.org:8888/cookie-parser-result?mozilla0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0015", + &["six", "seven"], + "http://home.example.org:8888/cookie-parser-result?mozilla0015"); assert_eq!(&r, ""); } #[test] fn test_mozilla0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0016", - &["six", "seven", " =eight"], - "http://home.example.org:8888/cookie-parser-result?mozilla0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0016", + &["six", "seven", " =eight"], + "http://home.example.org:8888/cookie-parser-result?mozilla0016"); assert_eq!(&r, ""); } #[test] fn test_mozilla0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?mozilla0017", - &["six", "seven", " =eight", "test=six"], - "http://home.example.org:8888/cookie-parser-result?mozilla0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?mozilla0017", + &["six", "seven", " =eight", "test=six"], + "http://home.example.org:8888/cookie-parser-result?mozilla0017"); assert_eq!(&r, "test=six"); } #[test] fn test_name0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0001", - &["a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0001", + &["a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0001"); assert_eq!(&r, "a=bar"); } #[test] fn test_name0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0002", - &["1=bar"], - "http://home.example.org:8888/cookie-parser-result?name0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0002", + &["1=bar"], + "http://home.example.org:8888/cookie-parser-result?name0002"); assert_eq!(&r, "1=bar"); } #[test] fn test_name0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0003", - &["$=bar"], - "http://home.example.org:8888/cookie-parser-result?name0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0003", + &["$=bar"], + "http://home.example.org:8888/cookie-parser-result?name0003"); assert_eq!(&r, "$=bar"); } #[test] fn test_name0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0004", - &["!a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0004", + &["!a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0004"); assert_eq!(&r, "!a=bar"); } #[test] fn test_name0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0005", - &["@a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0005", + &["@a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0005"); assert_eq!(&r, "@a=bar"); } #[test] fn test_name0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0006", - &["#a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0006", + &["#a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0006"); assert_eq!(&r, "#a=bar"); } #[test] fn test_name0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0007", - &["$a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0007", + &["$a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0007"); assert_eq!(&r, "$a=bar"); } #[test] fn test_name0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0008", - &["%a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0008", + &["%a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0008"); assert_eq!(&r, "%a=bar"); } #[test] fn test_name0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0009", - &["^a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0009", + &["^a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0009"); assert_eq!(&r, "^a=bar"); } #[test] fn test_name0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0010", - &["&a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0010", + &["&a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0010"); assert_eq!(&r, "&a=bar"); } #[test] fn test_name0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0011", - &["*a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0011", + &["*a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0011"); assert_eq!(&r, "*a=bar"); } #[test] fn test_name0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0012", - &["(a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0012", + &["(a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0012"); assert_eq!(&r, "(a=bar"); } #[test] fn test_name0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0013", - &[")a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0013", + &[")a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0013"); assert_eq!(&r, ")a=bar"); } #[test] fn test_name0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0014", - &["-a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0014", + &["-a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0014"); assert_eq!(&r, "-a=bar"); } #[test] fn test_name0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0015", - &["_a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0015", + &["_a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0015"); assert_eq!(&r, "_a=bar"); } #[test] fn test_name0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0016", - &["+=bar"], - "http://home.example.org:8888/cookie-parser-result?name0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0016", + &["+=bar"], + "http://home.example.org:8888/cookie-parser-result?name0016"); assert_eq!(&r, "+=bar"); } #[test] fn test_name0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0017", - &["=a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0017", + &["=a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0017"); assert_eq!(&r, ""); } #[test] fn test_name0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0018", - &["a =bar"], - "http://home.example.org:8888/cookie-parser-result?name0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0018", + &["a =bar"], + "http://home.example.org:8888/cookie-parser-result?name0018"); assert_eq!(&r, "a=bar"); } #[test] fn test_name0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0019", - &["\"a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0019", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0019", + &["\"a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0019"); assert_eq!(&r, "\"a=bar"); } #[test] fn test_name0020() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0020", - &["\"a=b\"=bar"], - "http://home.example.org:8888/cookie-parser-result?name0020", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0020", + &["\"a=b\"=bar"], + "http://home.example.org:8888/cookie-parser-result?name0020"); assert_eq!(&r, "\"a=b\"=bar"); } #[test] fn test_name0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0021", - &["\"a=b\"=bar", "\"a=qux"], - "http://home.example.org:8888/cookie-parser-result?name0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0021", + &["\"a=b\"=bar", "\"a=qux"], + "http://home.example.org:8888/cookie-parser-result?name0021"); assert_eq!(&r, "\"a=qux"); } #[test] fn test_name0022() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0022", - &[" foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0022", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0022", + &[" foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0022"); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0023() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0023", - &["foo;bar=baz"], - "http://home.example.org:8888/cookie-parser-result?name0023", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0023", + &["foo;bar=baz"], + "http://home.example.org:8888/cookie-parser-result?name0023"); assert_eq!(&r, ""); } #[test] fn test_name0024() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0024", - &["$Version=1; foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0024", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0024", + &["$Version=1; foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0024"); assert_eq!(&r, "$Version=1"); } #[test] fn test_name0025() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0025", - &["===a=bar"], - "http://home.example.org:8888/cookie-parser-result?name0025", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0025", + &["===a=bar"], + "http://home.example.org:8888/cookie-parser-result?name0025"); assert_eq!(&r, ""); } #[test] fn test_name0026() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0026", - &["foo=bar"], - "http://home.example.org:8888/cookie-parser-result?name0026", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0026", + &["foo=bar"], + "http://home.example.org:8888/cookie-parser-result?name0026"); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0027() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0027", - &["foo=bar ;"], - "http://home.example.org:8888/cookie-parser-result?name0027", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0027", + &["foo=bar ;"], + "http://home.example.org:8888/cookie-parser-result?name0027"); assert_eq!(&r, "foo=bar"); } #[test] fn test_name0028() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0028", - &["=a"], - "http://home.example.org:8888/cookie-parser-result?name0028", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0028", + &["=a"], + "http://home.example.org:8888/cookie-parser-result?name0028"); assert_eq!(&r, ""); } #[test] fn test_name0029() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0029", - &["="], - "http://home.example.org:8888/cookie-parser-result?name0029", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0029", + &["="], + "http://home.example.org:8888/cookie-parser-result?name0029"); assert_eq!(&r, ""); } #[test] fn test_name0030() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0030", - &["foo bar=baz"], - "http://home.example.org:8888/cookie-parser-result?name0030", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0030", + &["foo bar=baz"], + "http://home.example.org:8888/cookie-parser-result?name0030"); assert_eq!(&r, "foo bar=baz"); } #[test] fn test_name0031() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0031", - &["\"foo;bar\"=baz"], - "http://home.example.org:8888/cookie-parser-result?name0031", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0031", + &["\"foo;bar\"=baz"], + "http://home.example.org:8888/cookie-parser-result?name0031"); assert_eq!(&r, ""); } #[test] fn test_name0032() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0032", - &["\"foo\\\"bar;baz\"=qux"], - "http://home.example.org:8888/cookie-parser-result?name0032", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0032", + &["\"foo\\\"bar;baz\"=qux"], + "http://home.example.org:8888/cookie-parser-result?name0032"); assert_eq!(&r, ""); } #[test] fn test_name0033() { - let r = run( - "http://home.example.org:8888/cookie-parser?name0033", - &["=foo=bar", "aaa"], - "http://home.example.org:8888/cookie-parser-result?name0033", - ); + let r = run("http://home.example.org:8888/cookie-parser?name0033", + &["=foo=bar", "aaa"], + "http://home.example.org:8888/cookie-parser-result?name0033"); assert_eq!(&r, ""); } #[test] fn test_optional_domain0030() { - let r = run( - "http://home.example.org:8888/cookie-parser?optional-domain0030", - &["foo=bar; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0030", - ); + let r = run("http://home.example.org:8888/cookie-parser?optional-domain0030", + &["foo=bar; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0030"); assert_eq!(&r, "foo=bar"); } #[test] fn test_optional_domain0041() { - let r = run( - "http://home.example.org:8888/cookie-parser?optional-domain0041", - &["foo=bar; domain=example.org; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0041", - ); + let r = run("http://home.example.org:8888/cookie-parser?optional-domain0041", + &["foo=bar; domain=example.org; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0041"); assert_eq!(&r, "foo=bar"); } #[test] fn test_optional_domain0042() { - let r = run( - "http://home.example.org:8888/cookie-parser?optional-domain0042", - &["foo=bar; domain=foo.example.org; domain="], - "http://home.example.org:8888/cookie-parser-result?optional-domain0042", - ); + let r = run("http://home.example.org:8888/cookie-parser?optional-domain0042", + &["foo=bar; domain=foo.example.org; domain="], + "http://home.example.org:8888/cookie-parser-result?optional-domain0042"); assert_eq!(&r, ""); } #[test] fn test_optional_domain0043() { - let r = run( - "http://home.example.org:8888/cookie-parser?optional-domain0043", - &["foo=bar; domain=foo.example.org; domain="], - "http://subdomain.home.example.org:8888/cookie-parser-result?optional-do\ - main0043", - ); + let r = run("http://home.example.org:8888/cookie-parser?optional-domain0043", + &["foo=bar; domain=foo.example.org; domain="], + "http://subdomain.home.example.org:8888/cookie-parser-result?optional-do\ +main0043"); assert_eq!(&r, ""); } #[test] fn test_ordering0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?ordering0001", - &[ - "key=val0;", - "key=val1; path=/cookie-parser-result", - "key=val2; path=/", - "key=val3; path=/bar", - "key=val4; domain=.example.org", - "key=val5; domain=.example.org; path=/cookie-parser-result/foo", - ], - "http://home.example.org:8888/cookie-parser-result/foo/baz?ordering0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?ordering0001", + &["key=val0;", + "key=val1; path=/cookie-parser-result", + "key=val2; path=/", + "key=val3; path=/bar", + "key=val4; domain=.example.org", + "key=val5; domain=.example.org; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result/foo/baz?ordering0001"); assert_eq!(&r, "key=val5; key=val1; key=val2; key=val4"); } #[test] fn test_path0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0001", - &["a=b; path=/", "x=y; path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?path0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0001", + &["a=b; path=/", "x=y; path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?path0001"); assert_eq!(&r, "x=y; a=b"); } #[test] fn test_path0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0002", - &["a=b; path=/cookie-parser-result", "x=y; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0002", + &["a=b; path=/cookie-parser-result", "x=y; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0002"); assert_eq!(&r, "a=b; x=y"); } #[test] fn test_path0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0003", - &["x=y; path=/", "a=b; path=/cookie-parser-result"], - "http://home.example.org:8888/cookie-parser-result?path0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0003", + &["x=y; path=/", "a=b; path=/cookie-parser-result"], + "http://home.example.org:8888/cookie-parser-result?path0003"); assert_eq!(&r, "a=b; x=y"); } #[test] fn test_path0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0004", - &["x=y; path=/cookie-parser-result", "a=b; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0004", + &["x=y; path=/cookie-parser-result", "a=b; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0004"); assert_eq!(&r, "x=y; a=b"); } #[test] fn test_path0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0005", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result?path0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0005", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result?path0005"); assert_eq!(&r, ""); } #[test] fn test_path0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0006", - &["foo=bar", "foo=qux; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result?path0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0006", + &["foo=bar", "foo=qux; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result?path0006"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0007() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0007", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result/foo?path0007", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0007", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result/foo?path0007"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0008() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0008", - &["foo=bar; path=/cookie-parser-result/foo"], - "http://home.example.org:8888/cookie-parser-result/bar?path0008", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0008", + &["foo=bar; path=/cookie-parser-result/foo"], + "http://home.example.org:8888/cookie-parser-result/bar?path0008"); assert_eq!(&r, ""); } #[test] fn test_path0009() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0009", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo?path0009", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0009", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo?path0009"); assert_eq!(&r, ""); } #[test] fn test_path0010() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0010", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0010", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0010", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0010"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0011() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0011", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/bar/qux?path0011", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0011", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/bar/qux?path0011"); assert_eq!(&r, ""); } #[test] fn test_path0012() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0012", - &["foo=bar; path=/cookie-parser-result/foo/qux"], - "http://home.example.org:8888/cookie-parser-result/foo/baz?path0012", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0012", + &["foo=bar; path=/cookie-parser-result/foo/qux"], + "http://home.example.org:8888/cookie-parser-result/foo/baz?path0012"); assert_eq!(&r, ""); } #[test] fn test_path0013() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0013", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/baz?path0013", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0013", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/baz?path0013"); assert_eq!(&r, ""); } #[test] fn test_path0014() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0014", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0014", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0014", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0014"); assert_eq!(&r, ""); } #[test] fn test_path0015() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0015", - &["foo=bar; path=/cookie-parser-result/foo/qux/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux/?path0015", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0015", + &["foo=bar; path=/cookie-parser-result/foo/qux/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux/?path0015"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0016() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0016", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0016", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0016", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0016"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0017() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0017", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/foo//qux?path0017", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0017", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/foo//qux?path0017"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0018() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0018", - &["foo=bar; path=/cookie-parser-result/foo/"], - "http://home.example.org:8888/cookie-parser-result/fooqux?path0018", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0018", + &["foo=bar; path=/cookie-parser-result/foo/"], + "http://home.example.org:8888/cookie-parser-result/fooqux?path0018"); assert_eq!(&r, ""); } #[test] fn test_path0019() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0019", - &["foo=bar; path"], - "http://home.example.org:8888/cookie-parser-result?path0019", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0019", + &["foo=bar; path"], + "http://home.example.org:8888/cookie-parser-result?path0019"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0020() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0020", - &["foo=bar; path="], - "http://home.example.org:8888/cookie-parser-result?path0020", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0020", + &["foo=bar; path="], + "http://home.example.org:8888/cookie-parser-result?path0020"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0021() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0021", - &["foo=bar; path=/"], - "http://home.example.org:8888/cookie-parser-result?path0021", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0021", + &["foo=bar; path=/"], + "http://home.example.org:8888/cookie-parser-result?path0021"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0022() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0022", - &["foo=bar; path= /"], - "http://home.example.org:8888/cookie-parser-result?path0022", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0022", + &["foo=bar; path= /"], + "http://home.example.org:8888/cookie-parser-result?path0022"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0023() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0023", - &["foo=bar; Path=/cookie-PARSER-result"], - "http://home.example.org:8888/cookie-parser-result?path0023", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0023", + &["foo=bar; Path=/cookie-PARSER-result"], + "http://home.example.org:8888/cookie-parser-result?path0023"); assert_eq!(&r, ""); } #[test] fn test_path0024() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0024", - &["foo=bar; path=/cookie-parser-result/foo/qux?"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0024", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0024", + &["foo=bar; path=/cookie-parser-result/foo/qux?"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0024"); assert_eq!(&r, ""); } #[test] fn test_path0025() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0025", - &["foo=bar; path=/cookie-parser-result/foo/qux#"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0025", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0025", + &["foo=bar; path=/cookie-parser-result/foo/qux#"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0025"); assert_eq!(&r, ""); } #[test] fn test_path0026() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0026", - &["foo=bar; path=/cookie-parser-result/foo/qux;"], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0026", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0026", + &["foo=bar; path=/cookie-parser-result/foo/qux;"], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0026"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0027() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0027", - &["foo=bar; path=\"/cookie-parser-result/foo/qux;\""], - "http://home.example.org:8888/cookie-parser-result/foo/qux?path0027", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0027", + &["foo=bar; path=\"/cookie-parser-result/foo/qux;\""], + "http://home.example.org:8888/cookie-parser-result/foo/qux?path0027"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0028() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0028", - &["foo=bar; path=/cookie-parser-result/f%6Fo/bar"], - "http://home.example.org:8888/cookie-parser-result/foo/bar?path0028", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0028", + &["foo=bar; path=/cookie-parser-result/f%6Fo/bar"], + "http://home.example.org:8888/cookie-parser-result/foo/bar?path0028"); assert_eq!(&r, ""); } #[test] fn test_path0029() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0029", - &[ - "a=b; \tpath\t=\t/cookie-parser-result", - "x=y; \tpath\t=\t/book", - ], - "http://home.example.org:8888/cookie-parser-result?path0029", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0029", + &["a=b; \tpath\t=\t/cookie-parser-result", "x=y; \tpath\t=\t/book"], + "http://home.example.org:8888/cookie-parser-result?path0029"); assert_eq!(&r, "a=b"); } #[test] fn test_path0030() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0030", - &["foo=bar; path=/dog; path="], - "http://home.example.org:8888/cookie-parser-result?path0030", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0030", + &["foo=bar; path=/dog; path="], + "http://home.example.org:8888/cookie-parser-result?path0030"); assert_eq!(&r, "foo=bar"); } #[test] fn test_path0031() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0031", - &["foo=bar; path=; path=/dog"], - "http://home.example.org:8888/cookie-parser-result?path0031", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0031", + &["foo=bar; path=; path=/dog"], + "http://home.example.org:8888/cookie-parser-result?path0031"); assert_eq!(&r, ""); } #[test] fn test_path0032() { - let r = run( - "http://home.example.org:8888/cookie-parser?path0032", - &[ - "foo=bar; path=/cookie-parser-result", - "foo=qux; path=/cookie-parser-result/", - ], - "http://home.example.org:8888/cookie-parser-result/dog?path0032", - ); + let r = run("http://home.example.org:8888/cookie-parser?path0032", + &["foo=bar; path=/cookie-parser-result", "foo=qux; path=/cookie-parser-result/"], + "http://home.example.org:8888/cookie-parser-result/dog?path0032"); assert_eq!(&r, "foo=qux; foo=bar"); } #[test] fn test_value0001() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0001", - &["foo= bar"], - "http://home.example.org:8888/cookie-parser-result?value0001", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0001", + &["foo= bar"], + "http://home.example.org:8888/cookie-parser-result?value0001"); assert_eq!(&r, "foo=bar"); } #[test] fn test_value0002() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0002", - &["foo=\"bar\""], - "http://home.example.org:8888/cookie-parser-result?value0002", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0002", + &["foo=\"bar\""], + "http://home.example.org:8888/cookie-parser-result?value0002"); assert_eq!(&r, "foo=\"bar\""); } #[test] fn test_value0003() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0003", - &["foo=\" bar \""], - "http://home.example.org:8888/cookie-parser-result?value0003", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0003", + &["foo=\" bar \""], + "http://home.example.org:8888/cookie-parser-result?value0003"); assert_eq!(&r, "foo=\" bar \""); } #[test] fn test_value0004() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0004", - &["foo=\"bar;baz\""], - "http://home.example.org:8888/cookie-parser-result?value0004", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0004", + &["foo=\"bar;baz\""], + "http://home.example.org:8888/cookie-parser-result?value0004"); assert_eq!(&r, "foo=\"bar"); } #[test] fn test_value0005() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0005", - &["foo=\"bar=baz\""], - "http://home.example.org:8888/cookie-parser-result?value0005", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0005", + &["foo=\"bar=baz\""], + "http://home.example.org:8888/cookie-parser-result?value0005"); assert_eq!(&r, "foo=\"bar=baz\""); } #[test] fn test_value0006() { - let r = run( - "http://home.example.org:8888/cookie-parser?value0006", - &["\tfoo\t=\tbar\t \t;\tttt"], - "http://home.example.org:8888/cookie-parser-result?value0006", - ); + let r = run("http://home.example.org:8888/cookie-parser?value0006", + &["\tfoo\t=\tbar\t \t;\tttt"], + "http://home.example.org:8888/cookie-parser-result?value0006"); assert_eq!(&r, "foo=bar"); } diff --git a/components/net/tests/data_loader.rs b/components/net/tests/data_loader.rs index 9996aed73e61..4ad73dee080a 100644 --- a/components/net/tests/data_loader.rs +++ b/components/net/tests/data_loader.rs @@ -2,24 +2,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::fetch; -use headers_core::HeaderMapExt; -use headers_ext::ContentType; +use fetch; +use hyper::header::ContentType; +use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value}; use hyper_serde::Serde; -use mime::{self, Mime}; +use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use net_traits::request::{Origin, Request}; use net_traits::response::ResponseBody; -use net_traits::{FetchMetadata, FilteredMetadata, NetworkError}; use servo_url::ServoUrl; use std::ops::Deref; #[cfg(test)] -fn assert_parse( - url: &'static str, - content_type: Option, - charset: Option<&str>, - data: Option<&[u8]>, -) { +fn assert_parse(url: &'static str, + content_type: Option, + charset: Option<&str>, + data: Option<&[u8]>) { let url = ServoUrl::parse(url).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -31,14 +28,11 @@ fn assert_parse( assert!(!response.is_network_error()); assert_eq!(response.headers.len(), 1); - let header_content_type = response.headers.typed_get::(); - assert_eq!(header_content_type, content_type); + let header_content_type = response.headers.get::(); + assert_eq!(header_content_type, content_type.as_ref()); let metadata = match response.metadata() { - Ok(FetchMetadata::Filtered { - filtered: FilteredMetadata::Basic(m), - .. - }) => m, + Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(m), .. }) => m, result => panic!(result), }; assert_eq!(metadata.content_type.map(Serde::into_inner), content_type); @@ -54,12 +48,7 @@ fn assert_parse( }, None => { assert!(response.is_network_error()); - assert_eq!( - response.metadata().err(), - Some(NetworkError::Internal( - "Decoding data URL failed".to_owned() - )) - ); + assert_eq!(response.metadata().err(), Some(NetworkError::Internal("Decoding data URL failed".to_owned()))); }, } } @@ -73,88 +62,78 @@ fn empty_invalid() { fn plain() { assert_parse( "data:,hello%20world", - Some(ContentType::from( - "text/plain; charset=US-ASCII".parse::().unwrap(), - )), - Some("us-ascii"), - Some(b"hello world"), - ); + Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, + vec!((Attr::Charset, Value::Ext("US-ASCII".to_owned())))))), + Some("US-ASCII"), + Some(b"hello world")); } #[test] fn plain_ct() { assert_parse( "data:text/plain,hello", - Some(ContentType::from(mime::TEXT_PLAIN)), + Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, vec!()))), None, - Some(b"hello"), - ); + Some(b"hello")); } #[test] fn plain_html() { assert_parse( "data:text/html,

Servo

", - Some(ContentType::from(mime::TEXT_HTML)), + Some(ContentType(Mime(TopLevel::Text, SubLevel::Html, vec!()))), None, - Some(b"

Servo

"), - ); + Some(b"

Servo

")); } #[test] fn plain_charset() { assert_parse( "data:text/plain;charset=latin1,hello", - Some(ContentType::from( - "text/plain; charset=latin1".parse::().unwrap(), - )), + Some(ContentType(Mime(TopLevel::Text, + SubLevel::Plain, + vec!((Attr::Charset, Value::Ext("latin1".to_owned())))))), Some("latin1"), - Some(b"hello"), - ); + Some(b"hello")); } #[test] fn plain_only_charset() { assert_parse( "data:;charset=utf-8,hello", - Some(ContentType::from(mime::TEXT_PLAIN_UTF_8)), + Some(ContentType(Mime(TopLevel::Text, + SubLevel::Plain, + vec!((Attr::Charset, Value::Utf8))))), Some("utf-8"), - Some(b"hello"), - ); + Some(b"hello")); } #[test] fn base64() { assert_parse( "data:;base64,C62+7w==", - Some(ContentType::from( - "text/plain; charset=US-ASCII".parse::().unwrap(), - )), - Some("us-ascii"), - Some(&[0x0B, 0xAD, 0xBE, 0xEF]), - ); + Some(ContentType(Mime(TopLevel::Text, + SubLevel::Plain, + vec!((Attr::Charset, Value::Ext("US-ASCII".to_owned())))))), + Some("US-ASCII"), + Some(&[0x0B, 0xAD, 0xBE, 0xEF])); } #[test] fn base64_ct() { assert_parse( "data:application/octet-stream;base64,C62+7w==", - Some(ContentType::from(mime::APPLICATION_OCTET_STREAM)), + Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_owned()), vec!()))), None, - Some(&[0x0B, 0xAD, 0xBE, 0xEF]), - ); + Some(&[0x0B, 0xAD, 0xBE, 0xEF])); } #[test] fn base64_charset() { assert_parse( "data:text/plain;charset=koi8-r;base64,8PLl9+XkIO3l5Pfl5A==", - Some(ContentType::from( - "text/plain; charset=koi8-r".parse::().unwrap(), - )), + Some(ContentType(Mime(TopLevel::Text, SubLevel::Plain, + vec!((Attr::Charset, Value::Ext("koi8-r".to_owned())))))), Some("koi8-r"), - Some(&[ - 0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4, - ]), - ); + Some(&[0xF0, 0xF2, 0xE5, 0xF7, 0xE5, 0xE4, 0x20, 0xED, 0xE5, 0xE4, 0xF7, 0xE5, 0xE4])); } diff --git a/components/net/tests/fetch.rs b/components/net/tests/fetch.rs index 2414bb153e9c..2e33727e37f8 100644 --- a/components/net/tests/fetch.rs +++ b/components/net/tests/fetch.rs @@ -2,60 +2,56 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::fetch_with_context; -use crate::fetch_with_cors_cache; -use crate::http_loader::{expect_devtools_http_request, expect_devtools_http_response}; -use crate::{ - create_embedder_proxy, fetch, make_server, make_ssl_server, new_fetch_context, - DEFAULT_USER_AGENT, -}; +use {DEFAULT_USER_AGENT, new_fetch_context, create_embedder_proxy, fetch, make_server}; use devtools_traits::HttpRequest as DevtoolsHttpRequest; use devtools_traits::HttpResponse as DevtoolsHttpResponse; -use headers_core::HeaderMapExt; -use headers_ext::{ - AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin, -}; -use headers_ext::{AccessControlAllowMethods, AccessControlMaxAge}; -use headers_ext::{ - CacheControl, ContentLength, ContentType, Expires, Host, LastModified, Pragma, UserAgent, -}; -use http::header::{self, HeaderMap, HeaderName, HeaderValue}; -use http::uri::Authority; -use http::{Method, StatusCode}; -use hyper::body::Body; -use hyper::{Request as HyperRequest, Response as HyperResponse}; -use mime::{self, Mime}; +use fetch_with_context; +use fetch_with_cors_cache; +use http_loader::{expect_devtools_http_request, expect_devtools_http_response}; +use hyper::LanguageTag; +use hyper::header::{Accept, AccessControlAllowCredentials, AccessControlAllowHeaders, AccessControlAllowOrigin}; +use hyper::header::{AcceptEncoding, AcceptLanguage, AccessControlAllowMethods, AccessControlMaxAge}; +use hyper::header::{AccessControlRequestHeaders, AccessControlRequestMethod, Date, UserAgent}; +use hyper::header::{CacheControl, ContentLanguage, ContentLength, ContentType, Expires, LastModified}; +use hyper::header::{Encoding, Location, Pragma, Quality, QualityItem, SetCookie, qitem}; +use hyper::header::{Headers, Host, HttpDate, Referer as HyperReferer}; +use hyper::method::Method; +use hyper::mime::{Mime, SubLevel, TopLevel}; +use hyper::server::{Request as HyperRequest, Response as HyperResponse, Server}; +use hyper::status::StatusCode; +use hyper::uri::RequestUri; +use hyper_openssl; use msg::constellation_msg::TEST_PIPELINE_ID; -use net::connector::create_ssl_connector_builder; +use net::connector::create_ssl_client; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::hsts::HstsEntry; use net::test::HttpState; -use net_traits::request::{Destination, Origin, RedirectMode, Referrer, Request, RequestMode}; -use net_traits::response::{CacheState, Response, ResponseBody, ResponseType}; use net_traits::IncludeSubdomains; use net_traits::NetworkError; use net_traits::ReferrerPolicy; +use net_traits::request::{Destination, Origin, RedirectMode, Referrer, Request, RequestMode}; +use net_traits::response::{CacheState, Response, ResponseBody, ResponseType}; use servo_channel::{channel, Sender}; use servo_url::{ImmutableOrigin, ServoUrl}; use std::fs::File; use std::io::Read; -use std::iter::FromIterator; use std::path::Path; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex}; -use std::time::{Duration, SystemTime}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use time::{self, Duration}; +use unicase::UniCase; // TODO write a struct that impls Handler for storing test values #[test] fn test_fetch_response_is_not_network_error() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -77,19 +73,16 @@ fn test_fetch_on_bad_port_is_network_error() { let fetch_response = fetch(&mut request, None); assert!(fetch_response.is_network_error()); let fetch_error = fetch_response.get_network_error().unwrap(); - assert_eq!( - fetch_error, - &NetworkError::Internal("Request attempted on bad port".into()) - ) + assert_eq!(fetch_error, &NetworkError::Internal("Request attempted on bad port".into())) } #[test] fn test_fetch_response_body_matches_const_message() { static MESSAGE: &'static [u8] = b"Hello World!"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -104,7 +97,7 @@ fn test_fetch_response_body_matches_const_message() { ResponseBody::Done(ref body) => { assert_eq!(&**body, MESSAGE); }, - _ => panic!(), + _ => panic!() }; } @@ -116,10 +109,7 @@ fn test_fetch_aboutblank() { request.referrer = Referrer::NoReferrer; let fetch_response = fetch(&mut request, None); assert!(!fetch_response.is_network_error()); - assert_eq!( - *fetch_response.body.lock().unwrap(), - ResponseBody::Done(vec![]) - ); + assert_eq!(*fetch_response.body.lock().unwrap(), ResponseBody::Done(vec![])); } #[test] @@ -140,12 +130,11 @@ fn test_fetch_blob() { let origin = ServoUrl::parse("http://www.example.org/").unwrap(); let (sender, receiver) = ipc::channel().unwrap(); - context - .filemanager - .promote_memory(blob_buf, true, sender, "http://www.example.org".into()); + context.filemanager.promote_memory(blob_buf, true, sender, "http://www.example.org".into()); let id = receiver.recv().unwrap().unwrap(); let url = ServoUrl::parse(&format!("blob:{}{}", origin.as_str(), id.simple())).unwrap(); + let mut request = Request::new(url, Some(Origin::Origin(origin.origin())), None); let fetch_response = fetch_with_context(&mut request, &context); @@ -153,27 +142,19 @@ fn test_fetch_blob() { assert_eq!(fetch_response.headers.len(), 2); - let content_type: Mime = fetch_response - .headers - .typed_get::() - .unwrap() - .into(); - assert_eq!(content_type, mime::TEXT_PLAIN); + let content_type: &ContentType = fetch_response.headers.get().unwrap(); + assert_eq!(**content_type, Mime(TopLevel::Text, SubLevel::Plain, vec![])); - let content_length: ContentLength = fetch_response.headers.typed_get().unwrap(); - assert_eq!(content_length.0, bytes.len() as u64); + let content_length: &ContentLength = fetch_response.headers.get().unwrap(); + assert_eq!(**content_length, bytes.len() as u64); - assert_eq!( - *fetch_response.body.lock().unwrap(), - ResponseBody::Done(bytes.to_vec()) - ); + assert_eq!(*fetch_response.body.lock().unwrap(), + ResponseBody::Done(bytes.to_vec())); } #[test] fn test_fetch_file() { - let path = Path::new("../../resources/servo.css") - .canonicalize() - .unwrap(); + let path = Path::new("../../resources/servo.css").canonicalize().unwrap(); let url = ServoUrl::from_file_path(path.clone()).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -181,12 +162,8 @@ fn test_fetch_file() { let fetch_response = fetch(&mut request, None); assert!(!fetch_response.is_network_error()); assert_eq!(fetch_response.headers.len(), 1); - let content_type: Mime = fetch_response - .headers - .typed_get::() - .unwrap() - .into(); - assert_eq!(content_type, mime::TEXT_CSS); + let content_type: &ContentType = fetch_response.headers.get().unwrap(); + assert_eq!(**content_type, Mime(TopLevel::Text, SubLevel::Css, vec![])); let resp_body = fetch_response.body.lock().unwrap(); let mut file = File::open(path).unwrap(); @@ -197,7 +174,7 @@ fn test_fetch_file() { ResponseBody::Done(ref val) => { assert_eq!(val, &bytes); }, - _ => panic!(), + _ => panic!() } } @@ -225,45 +202,20 @@ fn test_fetch_bogus_scheme() { fn test_cors_preflight_fetch() { static ACK: &'static [u8] = b"ACK"; let state = Arc::new(AtomicUsize::new(0)); - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 - { - assert!( - request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD) - ); - assert!( - !request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS) - ); - assert!( - !request - .headers() - .get(header::REFERER) - .unwrap() - .to_str() - .unwrap() - .contains("a.html") - ); - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - response - .headers_mut() - .typed_insert(AccessControlAllowCredentials); - response - .headers_mut() - .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { + assert!(request.headers.has::()); + assert!(!request.headers.has::()); + assert!(!request.headers.get::().unwrap().contains("a.html")); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.headers_mut().set(AccessControlAllowCredentials); + response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get])); } else { - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - *response.body_mut() = ACK.to_vec().into(); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.send(ACK).unwrap(); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let target_url = url.clone().join("a.html").unwrap(); @@ -279,7 +231,7 @@ fn test_cors_preflight_fetch() { assert!(!fetch_response.is_network_error()); match *fetch_response.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!(), + _ => panic!() }; } @@ -289,39 +241,20 @@ fn test_cors_preflight_cache_fetch() { let state = Arc::new(AtomicUsize::new(0)); let counter = state.clone(); let mut cache = CorsCache::new(); - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 - { - assert!( - request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD) - ); - assert!( - !request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS) - ); - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - response - .headers_mut() - .typed_insert(AccessControlAllowCredentials); - response - .headers_mut() - .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); - response - .headers_mut() - .typed_insert(AccessControlMaxAge::from(Duration::new(6000, 0))); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { + assert!(request.headers.has::()); + assert!(!request.headers.has::()); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.headers_mut().set(AccessControlAllowCredentials); + response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get])); + response.headers_mut().set(AccessControlMaxAge(6000)); } else { - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - *response.body_mut() = ACK.to_vec().into(); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.send(ACK).unwrap(); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(ImmutableOrigin::new_opaque()); let mut request = Request::new(url.clone(), Some(origin.clone()), None); @@ -341,16 +274,16 @@ fn test_cors_preflight_cache_fetch() { assert_eq!(1, counter.load(Ordering::SeqCst)); // The entry exists in the CORS-preflight cache - assert_eq!(true, cache.match_method(&wrapped_request0, Method::GET)); - assert_eq!(true, cache.match_method(&wrapped_request1, Method::GET)); + assert_eq!(true, cache.match_method(&wrapped_request0, Method::Get)); + assert_eq!(true, cache.match_method(&wrapped_request1, Method::Get)); match *fetch_response0.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!(), + _ => panic!() }; match *fetch_response1.body.lock().unwrap() { ResponseBody::Done(ref body) => assert_eq!(&**body, ACK), - _ => panic!(), + _ => panic!() }; } @@ -358,40 +291,23 @@ fn test_cors_preflight_cache_fetch() { fn test_cors_preflight_fetch_network_error() { static ACK: &'static [u8] = b"ACK"; let state = Arc::new(AtomicUsize::new(0)); - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - if request.method() == Method::OPTIONS && state.clone().fetch_add(1, Ordering::SeqCst) == 0 - { - assert!( - request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_METHOD) - ); - assert!( - !request - .headers() - .contains_key(header::ACCESS_CONTROL_REQUEST_HEADERS) - ); - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - response - .headers_mut() - .typed_insert(AccessControlAllowCredentials); - response - .headers_mut() - .typed_insert(AccessControlAllowMethods::from_iter(vec![Method::GET])); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + if request.method == Method::Options && state.clone().fetch_add(1, Ordering::SeqCst) == 0 { + assert!(request.headers.has::()); + assert!(!request.headers.has::()); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.headers_mut().set(AccessControlAllowCredentials); + response.headers_mut().set(AccessControlAllowMethods(vec![Method::Get])); } else { - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - *response.body_mut() = ACK.to_vec().into(); + response.headers_mut().set(AccessControlAllowOrigin::Any); + response.send(ACK).unwrap(); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(ImmutableOrigin::new_opaque()); let mut request = Request::new(url, Some(origin), None); - request.method = Method::from_bytes(b"CHICKEN").unwrap(); + request.method = Method::Extension("CHICKEN".to_owned()); request.referrer = Referrer::NoReferrer; request.use_cors_preflight = true; request.mode = RequestMode::CorsMode; @@ -404,19 +320,14 @@ fn test_cors_preflight_fetch_network_error() { #[test] fn test_fetch_response_is_basic_filtered() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response - .headers_mut() - .insert(header::SET_COOKIE, HeaderValue::from_static("")); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(SetCookie(vec![])); // this header is obsoleted, so hyper doesn't implement it, but it's still covered by the spec - response.headers_mut().insert( - HeaderName::from_static("set-cookie2"), - HeaderValue::from_bytes(&vec![]).unwrap(), - ); + response.headers_mut().set_raw("Set-Cookie2", vec![]); - *response.body_mut() = MESSAGE.to_vec().into(); + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -428,59 +339,39 @@ fn test_fetch_response_is_basic_filtered() { assert_eq!(fetch_response.response_type, ResponseType::Basic); let headers = fetch_response.headers; - assert!(!headers.contains_key(header::SET_COOKIE)); - assert!( - headers - .get(HeaderName::from_static("set-cookie2")) - .is_none() - ); + assert!(!headers.has::()); + assert!(headers.get_raw("Set-Cookie2").is_none()); } #[test] fn test_fetch_response_is_cors_filtered() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { + let handler = move |_: HyperRequest, mut response: HyperResponse| { // this is mandatory for the Cors Check to pass // TODO test using different url encodings with this value ie. punycode - response - .headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); + response.headers_mut().set(AccessControlAllowOrigin::Any); // these are the headers that should be kept after filtering - response.headers_mut().typed_insert(CacheControl::new()); - response.headers_mut().insert( - header::CONTENT_LANGUAGE, - HeaderValue::from_bytes(&vec![]).unwrap(), - ); - response - .headers_mut() - .typed_insert(ContentType::from(mime::TEXT_HTML)); - response - .headers_mut() - .typed_insert(Expires::from(SystemTime::now() + Duration::new(86400, 0))); - response - .headers_mut() - .typed_insert(LastModified::from(SystemTime::now())); - response.headers_mut().typed_insert(Pragma::no_cache()); + response.headers_mut().set(CacheControl(vec![])); + response.headers_mut().set(ContentLanguage(vec![])); + response.headers_mut().set(ContentType::html()); + response.headers_mut().set(Expires(HttpDate(time::now() + Duration::days(1)))); + response.headers_mut().set(LastModified(HttpDate(time::now()))); + response.headers_mut().set(Pragma::NoCache); // these headers should not be kept after filtering, even though they are given a pass - response - .headers_mut() - .insert(header::SET_COOKIE, HeaderValue::from_static("")); - response.headers_mut().insert( - HeaderName::from_static("set-cookie2"), - HeaderValue::from_bytes(&vec![]).unwrap(), + response.headers_mut().set(SetCookie(vec![])); + response.headers_mut().set_raw("Set-Cookie2", vec![]); + response.headers_mut().set( + AccessControlAllowHeaders(vec![ + UniCase("set-cookie".to_owned()), + UniCase("set-cookie2".to_owned()) + ]) ); - response - .headers_mut() - .typed_insert(AccessControlAllowHeaders::from_iter(vec![ - HeaderName::from_static("set-cookie"), - HeaderName::from_static("set-cookie2"), - ])); - - *response.body_mut() = MESSAGE.to_vec().into(); + + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); // an origin mis-match will stop it from defaulting to a basic filtered response let origin = Origin::Origin(ImmutableOrigin::new_opaque()); @@ -494,29 +385,25 @@ fn test_fetch_response_is_cors_filtered() { assert_eq!(fetch_response.response_type, ResponseType::Cors); let headers = fetch_response.headers; - assert!(headers.contains_key(header::CACHE_CONTROL)); - assert!(headers.contains_key(header::CONTENT_LANGUAGE)); - assert!(headers.contains_key(header::CONTENT_TYPE)); - assert!(headers.contains_key(header::EXPIRES)); - assert!(headers.contains_key(header::LAST_MODIFIED)); - assert!(headers.contains_key(header::PRAGMA)); - - assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); - assert!(!headers.contains_key(header::SET_COOKIE)); - assert!( - headers - .get(HeaderName::from_static("set-cookie2")) - .is_none() - ); + assert!(headers.has::()); + assert!(headers.has::()); + assert!(headers.has::()); + assert!(headers.has::()); + assert!(headers.has::()); + assert!(headers.has::()); + + assert!(!headers.has::()); + assert!(!headers.has::()); + assert!(headers.get_raw("Set-Cookie2").is_none()); } #[test] fn test_fetch_response_is_opaque_filtered() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); // an origin mis-match will fall through to an Opaque filtered response let origin = Origin::Origin(ImmutableOrigin::new_opaque()); @@ -532,40 +419,39 @@ fn test_fetch_response_is_opaque_filtered() { assert!(fetch_response.url_list.is_empty()); // this also asserts that status message is "the empty byte sequence" assert!(fetch_response.status.is_none()); - assert_eq!(fetch_response.headers, HeaderMap::new()); + assert_eq!(fetch_response.headers, Headers::new()); match *fetch_response.body.lock().unwrap() { - ResponseBody::Empty => {}, - _ => panic!(), + ResponseBody::Empty => { }, + _ => panic!() } match fetch_response.cache_state { - CacheState::None => {}, - _ => panic!(), + CacheState::None => { }, + _ => panic!() } } #[test] fn test_fetch_response_is_opaque_redirect_filtered() { static MESSAGE: &'static [u8] = b""; - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request - .uri() - .path() - .split("/") - .collect::() - .parse::() - .unwrap_or(0); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let redirects = match request.uri { + RequestUri::AbsolutePath(url) => + url.split("/").collect::().parse::().unwrap_or(0), + RequestUri::AbsoluteUri(url) => + url.path_segments().unwrap().next_back().unwrap().parse::().unwrap_or(0), + _ => panic!() + }; if redirects == 1 { - *response.body_mut() = MESSAGE.to_vec().into(); + response.send(MESSAGE).unwrap(); } else { - *response.status_mut() = StatusCode::FOUND; - response - .headers_mut() - .insert(header::LOCATION, HeaderValue::from_static("1")); + *response.status_mut() = StatusCode::Found; + let url = format!("{}", 1); + response.headers_mut().set(Location(url.to_owned())); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -579,14 +465,14 @@ fn test_fetch_response_is_opaque_redirect_filtered() { // this also asserts that status message is "the empty byte sequence" assert!(fetch_response.status.is_none()); - assert_eq!(fetch_response.headers, HeaderMap::new()); + assert_eq!(fetch_response.headers, Headers::new()); match *fetch_response.body.lock().unwrap() { - ResponseBody::Empty => {}, - _ => panic!(), + ResponseBody::Empty => { }, + _ => panic!() } match fetch_response.cache_state { - CacheState::None => {}, - _ => panic!(), + CacheState::None => { }, + _ => panic!() } } @@ -595,10 +481,10 @@ fn test_fetch_with_local_urls_only() { // If flag `local_urls_only` is set, fetching a non-local URL must result in network error. static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, server_url) = make_server(handler); + let (mut server, server_url) = make_server(handler); let do_fetch = |url: ServoUrl| { let origin = Origin::Origin(url.origin()); @@ -620,6 +506,7 @@ fn test_fetch_with_local_urls_only() { assert!(!local_response.is_network_error()); assert!(server_response.is_network_error()); } + // NOTE(emilio): If this test starts failing: // // openssl req -x509 -nodes -days 3650 -newkey rsa:2048 \ @@ -630,24 +517,22 @@ fn test_fetch_with_local_urls_only() { #[test] fn test_fetch_with_hsts() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt") - .canonicalize() - .unwrap(); - let key_path = Path::new("../../resources/privatekey_for_testing.key") - .canonicalize() + let cert_path = Path::new("../../resources/self_signed_certificate_for_testing.crt").canonicalize().unwrap(); + let key_path = Path::new("../../resources/privatekey_for_testing.key").canonicalize().unwrap(); + + let ssl = hyper_openssl::OpensslServer::from_files(key_path, cert_path.clone()) .unwrap(); - let (server, url) = make_ssl_server(handler, cert_path.clone(), key_path.clone()); + + //takes an address and something that implements hyper::net::Ssl + let mut server = Server::https("0.0.0.0:0", ssl).unwrap().handle_threads(handler, 1).unwrap(); let mut ca_content = String::new(); - File::open(cert_path) - .unwrap() - .read_to_string(&mut ca_content) - .unwrap(); - let ssl_client = create_ssl_connector_builder(&ca_content); + File::open(cert_path).unwrap().read_to_string(&mut ca_content).unwrap(); + let ssl_client = create_ssl_client(&ca_content); let context = FetchContext { state: Arc::new(HttpState::new(ssl_client)), @@ -659,30 +544,29 @@ fn test_fetch_with_hsts() { { let mut list = context.state.hsts_list.write().unwrap(); - list.push( - HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None).unwrap(), - ); + list.push(HstsEntry::new("localhost".to_owned(), IncludeSubdomains::NotIncluded, None) + .unwrap()); } + let url_string = format!("http://localhost:{}", server.socket.port()); + let url = ServoUrl::parse(&url_string).unwrap(); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); request.referrer = Referrer::NoReferrer; // Set the flag. request.local_urls_only = false; let response = fetch_with_context(&mut request, &context); - server.close(); - assert_eq!( - response.internal_response.unwrap().url().unwrap().scheme(), - "https" - ); + let _ = server.close(); + assert_eq!(response.internal_response.unwrap().url().unwrap().scheme(), + "https"); } #[test] fn test_fetch_with_sri_network_error() { static MESSAGE: &'static [u8] = b"alert('Hello, Network Error');"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -690,7 +574,7 @@ fn test_fetch_with_sri_network_error() { // To calulate hash use : // echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A request.integrity_metadata = - "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); + "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); // Set the flag. request.local_urls_only = false; @@ -703,10 +587,10 @@ fn test_fetch_with_sri_network_error() { #[test] fn test_fetch_with_sri_sucess() { static MESSAGE: &'static [u8] = b"alert('Hello, world.');"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -714,7 +598,7 @@ fn test_fetch_with_sri_sucess() { // To calulate hash use : // echo -n "alert('Hello, Network Error');" | openssl dgst -sha384 -binary | openssl base64 -A request.integrity_metadata = - "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); + "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO".to_owned(); // Set the flag. request.local_urls_only = false; @@ -728,25 +612,24 @@ fn test_fetch_with_sri_sucess() { #[test] fn test_fetch_blocked_nosniff() { #[inline] - fn test_nosniff_request(destination: Destination, mime: Mime, should_error: bool) { + fn test_nosniff_request(destination: Destination, + mime: Mime, + should_error: bool) { const MESSAGE: &'static [u8] = b""; - const HEADER: &'static str = "x-content-type-options"; + const HEADER: &'static str = "X-Content-Type-Options"; const VALUE: &'static [u8] = b"nosniff"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - let mime_header = ContentType::from(mime.clone()); - response.headers_mut().typed_insert(mime_header); - assert!(response.headers().contains_key(header::CONTENT_TYPE)); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + let mime_header = ContentType(mime.clone()); + response.headers_mut().set(mime_header); + assert!(response.headers().has::()); // Add the nosniff header - response.headers_mut().insert( - HeaderName::from_static(HEADER), - HeaderValue::from_bytes(VALUE).unwrap(), - ); + response.headers_mut().set_raw(HEADER, vec![VALUE.to_vec()]); - *response.body_mut() = MESSAGE.to_vec().into(); + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -758,9 +641,9 @@ fn test_fetch_blocked_nosniff() { } let tests = vec![ - (Destination::Script, mime::TEXT_JAVASCRIPT, false), - (Destination::Script, mime::TEXT_CSS, true), - (Destination::Style, mime::TEXT_CSS, false), + (Destination::Script, Mime(TopLevel::Text, SubLevel::Javascript, vec![]), false), + (Destination::Script, Mime(TopLevel::Text, SubLevel::Css, vec![]), true), + (Destination::Style, Mime(TopLevel::Text, SubLevel::Css, vec![]), false), ]; for test in tests { @@ -770,27 +653,25 @@ fn test_fetch_blocked_nosniff() { } fn setup_server_and_fetch(message: &'static [u8], redirect_cap: u32) -> Response { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request - .uri() - .path() - .split("/") - .collect::() - .parse::() - .unwrap_or(0); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let redirects = match request.uri { + RequestUri::AbsolutePath(url) => + url.split("/").collect::().parse::().unwrap_or(0), + RequestUri::AbsoluteUri(url) => + url.path_segments().unwrap().next_back().unwrap().parse::().unwrap_or(0), + _ => panic!() + }; if redirects >= redirect_cap { - *response.body_mut() = message.to_vec().into(); + response.send(message).unwrap(); } else { - *response.status_mut() = StatusCode::FOUND; + *response.status_mut() = StatusCode::Found; let url = format!("{redirects}", redirects = redirects + 1); - response - .headers_mut() - .insert(header::LOCATION, HeaderValue::from_str(&url).unwrap()); + response.headers_mut().set(Location(url.to_owned())); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -815,7 +696,7 @@ fn test_fetch_redirect_count_ceiling() { ResponseBody::Done(ref body) => { assert_eq!(&**body, MESSAGE); }, - _ => panic!(), + _ => panic!() }; } @@ -831,44 +712,38 @@ fn test_fetch_redirect_count_failure() { match *fetch_response.body.lock().unwrap() { ResponseBody::Done(_) | ResponseBody::Receiving(_) => panic!(), - _ => {}, + _ => { } }; } -fn test_fetch_redirect_updates_method_runner( - tx: Sender, - status_code: StatusCode, - method: Method, -) { +fn test_fetch_redirect_updates_method_runner(tx: Sender, status_code: StatusCode, method: Method) { let handler_method = method.clone(); let handler_tx = Arc::new(Mutex::new(tx)); - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request - .uri() - .path() - .split("/") - .collect::() - .parse::() - .unwrap_or(0); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let redirects = match request.uri { + RequestUri::AbsolutePath(url) => + url.split("/").collect::().parse::().unwrap_or(0), + RequestUri::AbsoluteUri(url) => + url.path_segments().unwrap().next_back().unwrap().parse::().unwrap_or(0), + _ => panic!() + }; let mut test_pass = true; if redirects == 0 { - *response.status_mut() = StatusCode::TEMPORARY_REDIRECT; - response - .headers_mut() - .insert(header::LOCATION, HeaderValue::from_static("1")); + *response.status_mut() = StatusCode::TemporaryRedirect; + response.headers_mut().set(Location("1".to_owned())); + } else if redirects == 1 { // this makes sure that the request method does't change from the wrong status code - if handler_method != Method::GET && request.method() == Method::GET { + if handler_method != Method::Get && request.method == Method::Get { test_pass = false; } *response.status_mut() = status_code; - response - .headers_mut() - .insert(header::LOCATION, HeaderValue::from_static("2")); - } else if request.method() != Method::GET { + response.headers_mut().set(Location("2".to_owned())); + + } else if request.method != Method::Get { test_pass = false; } @@ -876,9 +751,10 @@ fn test_fetch_redirect_updates_method_runner( if redirects > 0 { handler_tx.lock().unwrap().send(test_pass).unwrap(); } + }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -893,44 +769,36 @@ fn test_fetch_redirect_updates_method_runner( fn test_fetch_redirect_updates_method() { let (tx, rx) = channel(); - test_fetch_redirect_updates_method_runner( - tx.clone(), - StatusCode::MOVED_PERMANENTLY, - Method::POST, - ); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MovedPermanently, Method::Post); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.recv().unwrap(), true); // make sure the test doesn't send more data than expected assert_eq!(rx.try_recv().is_none(), true); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::FOUND, Method::POST); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::Found, Method::Post); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.try_recv().is_none(), true); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SEE_OTHER, Method::GET); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SeeOther, Method::Get); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.try_recv().is_none(), true); - let extension = Method::from_bytes(b"FOO").unwrap(); + let extension = Method::Extension("FOO".to_owned()); - test_fetch_redirect_updates_method_runner( - tx.clone(), - StatusCode::MOVED_PERMANENTLY, - extension.clone(), - ); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::MovedPermanently, extension.clone()); assert_eq!(rx.recv().unwrap(), true); // for MovedPermanently and Found, Method should only be changed if it was Post assert_eq!(rx.recv().unwrap(), false); assert_eq!(rx.try_recv().is_none(), true); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::FOUND, extension.clone()); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::Found, extension.clone()); assert_eq!(rx.recv().unwrap(), true); assert_eq!(rx.recv().unwrap(), false); assert_eq!(rx.try_recv().is_none(), true); - test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SEE_OTHER, extension.clone()); + test_fetch_redirect_updates_method_runner(tx.clone(), StatusCode::SeeOther, extension.clone()); assert_eq!(rx.recv().unwrap(), true); // for SeeOther, Method should always be changed, so this should be true assert_eq!(rx.recv().unwrap(), true); @@ -941,9 +809,9 @@ fn response_is_done(response: &Response) -> bool { let response_complete = match response.response_type { ResponseType::Default | ResponseType::Basic | ResponseType::Cors => { (*response.body.lock().unwrap()).is_done() - }, + } // if the internal response cannot have a body, it shouldn't block the "done" state - ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true, + ResponseType::Opaque | ResponseType::OpaqueRedirect | ResponseType::Error(..) => true }; let internal_complete = if let Some(ref res) = response.internal_response { @@ -958,10 +826,10 @@ fn response_is_done(response: &Response) -> bool { #[test] fn test_fetch_async_returns_complete_response() { static MESSAGE: &'static [u8] = b"this message should be retrieved in full"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -976,10 +844,10 @@ fn test_fetch_async_returns_complete_response() { #[test] fn test_opaque_filtered_fetch_async_returns_complete_response() { static MESSAGE: &'static [u8] = b""; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); // an origin mis-match will fall through to an Opaque filtered response let origin = Origin::Origin(ImmutableOrigin::new_opaque()); @@ -997,26 +865,25 @@ fn test_opaque_filtered_fetch_async_returns_complete_response() { #[test] fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() { static MESSAGE: &'static [u8] = b""; - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let redirects = request - .uri() - .path() - .split("/") - .collect::() - .parse::() - .unwrap_or(0); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let redirects = match request.uri { + RequestUri::AbsolutePath(url) => + url.split("/").collect::().parse::().unwrap_or(0), + RequestUri::AbsoluteUri(url) => + url.path_segments().unwrap().last().unwrap().parse::().unwrap_or(0), + _ => panic!() + }; if redirects == 1 { - *response.body_mut() = MESSAGE.to_vec().into(); + response.send(MESSAGE).unwrap(); } else { - *response.status_mut() = StatusCode::FOUND; - response - .headers_mut() - .insert(header::LOCATION, HeaderValue::from_static("1")); + *response.status_mut() = StatusCode::Found; + let url = format!("{}", 1); + response.headers_mut().set(Location(url.to_owned())); } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url, Some(origin), None); @@ -1034,11 +901,11 @@ fn test_opaque_redirect_filtered_fetch_async_returns_complete_response() { #[test] fn test_fetch_with_devtools() { static MESSAGE: &'static [u8] = b"Yay!"; - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.body_mut() = MESSAGE.to_vec().into(); + let handler = move |_: HyperRequest, response: HyperResponse| { + response.send(MESSAGE).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let origin = Origin::Origin(url.origin()); let mut request = Request::new(url.clone(), Some(origin), Some(TEST_PIPELINE_ID)); @@ -1054,32 +921,36 @@ fn test_fetch_with_devtools() { let mut devhttpresponse = expect_devtools_http_response(&devtools_port); //Creating default headers for request - let mut headers = HeaderMap::new(); + let mut headers = Headers::new(); + + headers.set(AcceptEncoding(vec![ + qitem(Encoding::Gzip), + qitem(Encoding::Deflate), + qitem(Encoding::EncodingExt("br".to_owned())) + ])); - headers.insert( - header::ACCEPT_ENCODING, - HeaderValue::from_static("gzip, deflate, br"), - ); - headers.typed_insert(Host::from( - format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) - .parse::() - .unwrap(), - )); + headers.set(Host { hostname: url.host_str().unwrap().to_owned() , port: url.port().to_owned() }); - headers.insert(header::ACCEPT, HeaderValue::from_static("*/*")); + let accept = Accept(vec![qitem(Mime(TopLevel::Star, SubLevel::Star, vec![]))]); + headers.set(accept); - headers.insert( - header::ACCEPT_LANGUAGE, - HeaderValue::from_static("en-US, en; q=0.5"), - ); + let mut en_us: LanguageTag = Default::default(); + en_us.language = Some("en".to_owned()); + en_us.region = Some("US".to_owned()); + let mut en: LanguageTag = Default::default(); + en.language = Some("en".to_owned()); + headers.set(AcceptLanguage(vec![ + qitem(en_us), + QualityItem::new(en, Quality(500)), + ])); - headers.typed_insert::(DEFAULT_USER_AGENT.parse().unwrap()); + headers.set(UserAgent(DEFAULT_USER_AGENT.to_owned())); let httprequest = DevtoolsHttpRequest { url: url, - method: Method::GET, + method: Method::Get, headers: headers, - body: Some(vec![]), + body: None, pipeline_id: TEST_PIPELINE_ID, startedDateTime: devhttprequest.startedDateTime, timeStamp: devhttprequest.timeStamp, @@ -1089,13 +960,9 @@ fn test_fetch_with_devtools() { }; let content = "Yay!"; - let mut response_headers = HeaderMap::new(); - response_headers.typed_insert(ContentLength(content.len() as u64)); - devhttpresponse - .headers - .as_mut() - .unwrap() - .remove(header::DATE); + let mut response_headers = Headers::new(); + response_headers.set(ContentLength(content.len() as u64)); + devhttpresponse.headers.as_mut().unwrap().remove::(); let httpresponse = DevtoolsHttpResponse { headers: Some(response_headers), diff --git a/components/net/tests/filemanager_thread.rs b/components/net/tests/filemanager_thread.rs index 501413267225..8612bdae6729 100644 --- a/components/net/tests/filemanager_thread.rs +++ b/components/net/tests/filemanager_thread.rs @@ -2,14 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::create_embedder_proxy; +use create_embedder_proxy; use embedder_traits::FilterPattern; use ipc_channel::ipc; use net::filemanager_thread::FileManager; use net_traits::blob_url_store::BlobURLStoreError; -use net_traits::filemanager_thread::{ - FileManagerThreadError, FileManagerThreadMsg, ReadFileProgress, -}; +use net_traits::filemanager_thread::{FileManagerThreadMsg, FileManagerThreadError, ReadFileProgress}; use servo_config::prefs::{PrefValue, PREFS}; use std::fs::File; use std::io::Read; @@ -18,18 +16,14 @@ use std::path::PathBuf; #[test] fn test_filemanager() { let filemanager = FileManager::new(create_embedder_proxy()); - PREFS.set( - "dom.testing.htmlinputelement.select_files.enabled", - PrefValue::Boolean(true), - ); + PREFS.set("dom.testing.htmlinputelement.select_files.enabled", PrefValue::Boolean(true)); // Try to open a dummy file "components/net/tests/test.jpeg" in tree let mut handler = File::open("tests/test.jpeg").expect("test.jpeg is stolen"); let mut test_file_content = vec![]; - handler - .read_to_end(&mut test_file_content) - .expect("Read components/net/tests/test.jpeg error"); + handler.read_to_end(&mut test_file_content) + .expect("Read components/net/tests/test.jpeg error"); let patterns = vec![FilterPattern(".txt".to_string())]; let origin = "test.com".to_string(); @@ -37,16 +31,10 @@ fn test_filemanager() { { // Try to select a dummy file "components/net/tests/test.jpeg" let (tx, rx) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::SelectFile( - patterns.clone(), - tx, - origin.clone(), - Some("tests/test.jpeg".to_string()), - )); - let selected = rx - .recv() - .expect("Broken channel") - .expect("The file manager failed to find test.jpeg"); + filemanager.handle(FileManagerThreadMsg::SelectFile(patterns.clone(), tx, origin.clone(), + Some("tests/test.jpeg".to_string()))); + let selected = rx.recv().expect("Broken channel") + .expect("The file manager failed to find test.jpeg"); // Expecting attributes conforming the spec assert_eq!(selected.filename, PathBuf::from("test.jpeg")); @@ -55,35 +43,24 @@ fn test_filemanager() { // Test by reading, expecting same content { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::ReadFile( - tx2, - selected.id.clone(), - false, - origin.clone(), - )); + filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone())); let msg = rx2.recv().expect("Broken channel"); - if let ReadFileProgress::Meta(blob_buf) = - msg.expect("File manager reading failure is unexpected") - { + if let ReadFileProgress::Meta(blob_buf) = msg.expect("File manager reading failure is unexpected") { let mut bytes = blob_buf.bytes; loop { - match rx2 - .recv() - .expect("Broken channel") - .expect("File manager reading failure is unexpected") - { + match rx2.recv().expect("Broken channel").expect("File manager reading failure is unexpected") { ReadFileProgress::Meta(_) => { panic!("Invalid FileManager reply"); - }, + } ReadFileProgress::Partial(mut bytes_in) => { bytes.append(&mut bytes_in); - }, + } ReadFileProgress::EOF => { break; - }, + } } } @@ -96,11 +73,7 @@ fn test_filemanager() { // Delete the id { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::DecRef( - selected.id.clone(), - origin.clone(), - tx2, - )); + filemanager.handle(FileManagerThreadMsg::DecRef(selected.id.clone(), origin.clone(), tx2)); let ret = rx2.recv().expect("Broken channel"); assert!(ret.is_ok(), "DecRef is not okay"); @@ -109,26 +82,15 @@ fn test_filemanager() { // Test by reading again, expecting read error because we invalidated the id { let (tx2, rx2) = ipc::channel().unwrap(); - filemanager.handle(FileManagerThreadMsg::ReadFile( - tx2, - selected.id.clone(), - false, - origin.clone(), - )); + filemanager.handle(FileManagerThreadMsg::ReadFile(tx2, selected.id.clone(), false, origin.clone())); let msg = rx2.recv().expect("Broken channel"); match msg { - Err(FileManagerThreadError::BlobURLStoreError( - BlobURLStoreError::InvalidFileID, - )) => {}, + Err(FileManagerThreadError::BlobURLStoreError(BlobURLStoreError::InvalidFileID)) => {}, other => { - assert!( - false, - "Get unexpected response after deleting the id: {:?}", - other - ); - }, + assert!(false, "Get unexpected response after deleting the id: {:?}", other); + } } } } diff --git a/components/net/tests/hsts.rs b/components/net/tests/hsts.rs index 9389c5861102..3c857edc5e1e 100644 --- a/components/net/tests/hsts.rs +++ b/components/net/tests/hsts.rs @@ -5,6 +5,7 @@ use net::hsts::{HstsEntry, HstsList}; use net_traits::IncludeSubdomains; use std::collections::HashMap; +use time; #[test] fn test_hsts_entry_is_not_expired_when_it_has_no_timestamp() { @@ -12,7 +13,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_timestamp() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(20), - timestamp: None, + timestamp: None }; assert!(!entry.is_expired()); @@ -24,7 +25,7 @@ fn test_hsts_entry_is_not_expired_when_it_has_no_max_age() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: None, - timestamp: Some(time::get_time().sec as u64), + timestamp: Some(time::get_time().sec as u64) }; assert!(!entry.is_expired()); @@ -36,7 +37,7 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(10), - timestamp: Some(time::get_time().sec as u64 - 20u64), + timestamp: Some(time::get_time().sec as u64 - 20u64) }; assert!(entry.is_expired()); @@ -45,9 +46,7 @@ fn test_hsts_entry_is_expired_when_it_has_reached_its_max_age() { #[test] fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() { let entry = HstsEntry::new( - "2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(), - IncludeSubdomains::NotIncluded, - None, + "2001:0db8:0000:0000:0000:ff00:0042:8329".to_owned(), IncludeSubdomains::NotIncluded, None ); assert!(entry.is_none(), "able to create HstsEntry with IPv6 host"); @@ -55,7 +54,9 @@ fn test_hsts_entry_cant_be_created_with_ipv6_address_as_host() { #[test] fn test_hsts_entry_cant_be_created_with_ipv4_address_as_host() { - let entry = HstsEntry::new("4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None); + let entry = HstsEntry::new( + "4.4.4.4".to_owned(), IncludeSubdomains::NotIncluded, None + ); assert!(entry.is_none(), "able to create HstsEntry with IPv4 host"); } @@ -65,33 +66,15 @@ fn test_base_domain_in_entries_map() { let entries_map = HashMap::new(); let mut list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; - list.push( - HstsEntry::new( - "servo.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); - list.push( - HstsEntry::new( - "firefox.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); - list.push( - HstsEntry::new( - "bugzilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); + list.push(HstsEntry::new("servo.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); + list.push(HstsEntry::new("firefox.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); + list.push(HstsEntry::new("bugzilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); assert_eq!(list.entries_map.len(), 2); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 2); @@ -100,29 +83,14 @@ fn test_base_domain_in_entries_map() { #[test] fn test_push_entry_with_0_max_age_evicts_entry_from_list() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![ - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - Some(500000u64), - ) - .unwrap(), - ], - ); + entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, Some(500000u64)).unwrap())); let mut list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; - list.push( - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - Some(0), - ) - .unwrap(), - ); + list.push(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, Some(0)).unwrap()); assert_eq!(list.is_host_secure("mozilla.org"), false) } @@ -130,22 +98,14 @@ fn test_push_entry_with_0_max_age_evicts_entry_from_list() { #[test] fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_already_matched() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], - ); + entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap())); let mut list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; - list.push( - HstsEntry::new( - "servo.mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); + list.push(HstsEntry::new("servo.mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1) } @@ -153,24 +113,16 @@ fn test_push_entry_to_hsts_list_should_not_add_subdomains_whose_superdomain_is_a #[test] fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_subdomains() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], - ); + entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap())); let mut list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(list.is_host_secure("servo.mozilla.org")); - list.push( - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); + list.push(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); assert!(!list.is_host_secure("servo.mozilla.org")) } @@ -178,29 +130,14 @@ fn test_push_entry_to_hsts_list_should_update_existing_domain_entrys_include_sub #[test] fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![ - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ], - ); + entries_map.insert("mozilla.org".to_owned(), vec!(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap())); let mut list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; - list.push( - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ); + list.push(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()); assert_eq!(list.entries_map.get("mozilla.org").unwrap().len(), 1) } @@ -208,16 +145,16 @@ fn test_push_entry_to_hsts_list_should_not_create_duplicate_entry() { #[test] fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() { let mut list = HstsList { - entries_map: HashMap::new(), + entries_map: HashMap::new() }; assert!(!list.is_host_secure("mozilla.org")); assert!(!list.is_host_secure("bugzilla.org")); - list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()); - list.push( - HstsEntry::new("bugzilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap(), - ); + list.push(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()); + list.push(HstsEntry::new("bugzilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()); assert!(list.is_host_secure("mozilla.org")); assert!(list.is_host_secure("bugzilla.org")); @@ -226,12 +163,13 @@ fn test_push_multiple_entrie_to_hsts_list_should_add_them_all() { #[test] fn test_push_entry_to_hsts_list_should_add_an_entry() { let mut list = HstsList { - entries_map: HashMap::new(), + entries_map: HashMap::new() }; assert!(!list.is_host_secure("mozilla.org")); - list.push(HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()); + list.push(HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()); assert!(list.is_host_secure("mozilla.org")); } @@ -239,43 +177,34 @@ fn test_push_entry_to_hsts_list_should_add_an_entry() { #[test] fn test_parse_hsts_preload_should_return_none_when_json_invalid() { let mock_preload_content = "derp"; - assert!( - HstsList::from_preload(mock_preload_content).is_none(), - "invalid preload list should not have parsed" - ) + assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed") } #[test] fn test_parse_hsts_preload_should_return_none_when_json_contains_no_entries_map_key() { let mock_preload_content = "{\"nothing\": \"to see here\"}"; - assert!( - HstsList::from_preload(mock_preload_content).is_none(), - "invalid preload list should not have parsed" - ) + assert!(HstsList::from_preload(mock_preload_content).is_none(), "invalid preload list should not have parsed") } #[test] fn test_parse_hsts_preload_should_decode_host_and_includes_subdomains() { let mock_preload_content = "{\ - \"entries\": [\ - {\"host\": \"mozilla.org\",\ - \"include_subdomains\": false}\ - ]\ + \"entries\": [\ + {\"host\": \"mozilla.org\",\ + \"include_subdomains\": false}\ + ]\ }"; let hsts_list = HstsList::from_preload(mock_preload_content); let entries_map = hsts_list.unwrap().entries_map; - assert_eq!( - entries_map.get("mozilla.org").unwrap()[0].host, - "mozilla.org" - ); + assert_eq!(entries_map.get("mozilla.org").unwrap()[0].host, "mozilla.org"); assert!(!entries_map.get("mozilla.org").unwrap()[0].include_subdomains); } #[test] fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() { let hsts_list = HstsList { - entries_map: HashMap::new(), + entries_map: HashMap::new() }; assert!(!hsts_list.is_host_secure("mozilla.org")); @@ -284,20 +213,11 @@ fn test_hsts_list_with_no_entries_map_does_not_is_host_secure() { #[test] fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![ - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ], - ); + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(hsts_list.is_host_secure("mozilla.org")); @@ -306,12 +226,10 @@ fn test_hsts_list_with_exact_domain_entry_is_is_host_secure() { #[test] fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], - ); + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(hsts_list.is_host_secure("servo.mozilla.org")); @@ -320,19 +238,10 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_true_is_is_host_secu #[test] fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![ - HstsEntry::new( - "mozilla.org".to_owned(), - IncludeSubdomains::NotIncluded, - None, - ) - .unwrap(), - ], - ); + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::NotIncluded, None).unwrap()]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(!hsts_list.is_host_secure("servo.mozilla.org")); @@ -341,12 +250,10 @@ fn test_hsts_list_with_subdomain_when_include_subdomains_is_false_is_not_is_host #[test] fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], - ); + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(!hsts_list.is_host_secure("servo-mozilla.org")); @@ -355,12 +262,10 @@ fn test_hsts_list_with_subdomain_when_host_is_not_a_subdomain_is_not_is_host_sec #[test] fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry::new("mozilla.org".to_owned(), IncludeSubdomains::Included, None).unwrap()], - ); + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry::new("mozilla.org".to_owned(), + IncludeSubdomains::Included, None).unwrap()]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(hsts_list.is_host_secure("mozilla.org")); @@ -369,17 +274,14 @@ fn test_hsts_list_with_subdomain_when_host_is_exact_match_is_is_host_secure() { #[test] fn test_hsts_list_with_expired_entry_is_not_is_host_secure() { let mut entries_map = HashMap::new(); - entries_map.insert( - "mozilla.org".to_owned(), - vec![HstsEntry { + entries_map.insert("mozilla.org".to_owned(), vec![HstsEntry { host: "mozilla.org".to_owned(), include_subdomains: false, max_age: Some(20), - timestamp: Some(time::get_time().sec as u64 - 100u64), - }], - ); + timestamp: Some(time::get_time().sec as u64 - 100u64) + }]); let hsts_list = HstsList { - entries_map: entries_map, + entries_map: entries_map }; assert!(!hsts_list.is_host_secure("mozilla.org")); diff --git a/components/net/tests/http_cache.rs b/components/net/tests/http_cache.rs index f57d1b2df0ab..c63ba8131c7d 100644 --- a/components/net/tests/http_cache.rs +++ b/components/net/tests/http_cache.rs @@ -11,6 +11,7 @@ use net_traits::request::{Destination, Request, RequestInit}; use net_traits::response::{Response, ResponseBody}; use servo_url::ServoUrl; use std::sync::mpsc::channel; +use time; #[test] diff --git a/components/net/tests/http_loader.rs b/components/net/tests/http_loader.rs index ba8f2e1a3fd0..96c424469d1e 100644 --- a/components/net/tests/http_loader.rs +++ b/components/net/tests/http_loader.rs @@ -3,72 +3,72 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cookie_rs::Cookie as CookiePair; -use crate::fetch; -use crate::fetch_with_context; -use crate::make_server; -use crate::new_fetch_context; +use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use devtools_traits::HttpRequest as DevtoolsHttpRequest; use devtools_traits::HttpResponse as DevtoolsHttpResponse; -use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; -use flate2::write::{DeflateEncoder, GzEncoder}; +use fetch; +use fetch_with_context; use flate2::Compression; -use futures::{self, Future, Stream}; -use headers_core::HeaderMapExt; -use headers_ext::{ - AccessControlAllowOrigin, Authorization, Basic, ContentLength, Date, Host, Origin, -}; -use headers_ext::{StrictTransportSecurity, UserAgent}; -use http::header::{self, HeaderMap, HeaderValue}; -use http::uri::Authority; -use http::{Method, StatusCode}; -use hyper::body::Body; -use hyper::{Request as HyperRequest, Response as HyperResponse}; +use flate2::write::{DeflateEncoder, GzEncoder}; +use hyper::LanguageTag; +use hyper::header::{Accept, AcceptEncoding, ContentEncoding, ContentLength, Cookie as CookieHeader}; +use hyper::header::{AcceptLanguage, AccessControlAllowOrigin, Authorization, Basic, Date}; +use hyper::header::{Encoding, Headers, Host, Location, Origin, Quality, QualityItem, SetCookie, qitem}; +use hyper::header::{StrictTransportSecurity, UserAgent}; +use hyper::method::Method; +use hyper::mime::{Mime, SubLevel, TopLevel}; +use hyper::server::{Request as HyperRequest, Response as HyperResponse}; +use hyper::status::StatusCode; +use hyper::uri::RequestUri; +use make_server; use msg::constellation_msg::TEST_PIPELINE_ID; use net::cookie::Cookie; use net::cookie_storage::CookieStorage; use net::resource_thread::AuthCacheEntry; use net::test::replace_host_table; -use net_traits::request::{CredentialsMode, Destination, Request, RequestInit, RequestMode}; -use net_traits::response::ResponseBody; use net_traits::{CookieSource, NetworkError}; +use net_traits::request::{Request, RequestInit, RequestMode, CredentialsMode, Destination}; +use net_traits::response::ResponseBody; +use new_fetch_context; use servo_channel::{channel, Receiver}; -use servo_url::{ImmutableOrigin, ServoUrl}; +use servo_url::{ServoUrl, ImmutableOrigin}; use std::collections::HashMap; -use std::io::Write; -use std::str; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::io::{Read, Write}; +use std::str::FromStr; use std::sync::{Arc, Mutex, RwLock}; -use std::time::Duration; +use std::sync::atomic::{AtomicBool, Ordering}; fn mock_origin() -> ImmutableOrigin { ServoUrl::parse("http://servo.org").unwrap().origin() } -fn read_response(req: HyperRequest) -> impl Future { - req.into_body() - .concat2() - .and_then(|body| futures::future::ok(str::from_utf8(&body).unwrap().to_owned())) - .map_err(|_| ()) +fn read_response(reader: &mut Read) -> String { + let mut buf = vec![0; 1024]; + match reader.read(&mut buf) { + Ok(len) if len > 0 => { + unsafe { buf.set_len(len); } + String::from_utf8(buf).unwrap() + }, + Ok(_) => "".to_owned(), + Err(e) => panic!("problem reading response {}", e) + } } -fn assert_cookie_for_domain( - cookie_jar: &RwLock, - domain: &str, - cookie: Option<&str>, -) { +fn assert_cookie_for_domain(cookie_jar: &RwLock, domain: &str, cookie: Option<&str>) { let mut cookie_jar = cookie_jar.write().unwrap(); let url = ServoUrl::parse(&*domain).unwrap(); let cookies = cookie_jar.cookies_for_url(&url, CookieSource::HTTP); assert_eq!(cookies.as_ref().map(|c| &**c), cookie); } -pub fn expect_devtools_http_request( - devtools_port: &Receiver, -) -> DevtoolsHttpRequest { +pub fn expect_devtools_http_request(devtools_port: &Receiver) -> DevtoolsHttpRequest { match devtools_port.recv().unwrap() { - DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event)) => { + DevtoolsControlMsg::FromChrome( + ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event)) => { match net_event { - NetworkEvent::HttpRequest(httprequest) => httprequest, + NetworkEvent::HttpRequest(httprequest) => { + httprequest + }, _ => panic!("No HttpRequest Received"), } @@ -77,17 +77,17 @@ pub fn expect_devtools_http_request( } } -pub fn expect_devtools_http_response( - devtools_port: &Receiver, -) -> DevtoolsHttpResponse { +pub fn expect_devtools_http_response(devtools_port: &Receiver) -> DevtoolsHttpResponse { match devtools_port.recv().unwrap() { - DevtoolsControlMsg::FromChrome(ChromeToDevtoolsControlMsg::NetworkEvent( - _, - net_event_response, - )) => match net_event_response { - NetworkEvent::HttpResponse(httpresponse) => httpresponse, - - _ => panic!("No HttpResponse Received"), + DevtoolsControlMsg::FromChrome( + ChromeToDevtoolsControlMsg::NetworkEvent(_, net_event_response)) => { + match net_event_response { + NetworkEvent::HttpResponse(httpresponse) => { + httpresponse + }, + + _ => panic!("No HttpResponse Received"), + } }, _ => panic!("No HttpResponse Received"), } @@ -97,163 +97,125 @@ pub fn expect_devtools_http_response( fn test_check_default_headers_loaded_in_every_request() { let expected_headers = Arc::new(Mutex::new(None)); let expected_headers_clone = expected_headers.clone(); - let handler = move |request: HyperRequest, _: &mut HyperResponse| { - assert_eq!( - request.headers().clone(), - expected_headers_clone.lock().unwrap().take().unwrap() - ); + let handler = move |request: HyperRequest, _: HyperResponse| { + assert_eq!(request.headers, expected_headers_clone.lock().unwrap().take().unwrap()); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); - let mut headers = HeaderMap::new(); + let mut headers = Headers::new(); - headers.insert( - header::ACCEPT_ENCODING, - HeaderValue::from_static("gzip, deflate, br"), - ); + headers.set(AcceptEncoding(vec![qitem(Encoding::Gzip), + qitem(Encoding::Deflate), + qitem(Encoding::EncodingExt("br".to_owned()))])); - headers.typed_insert(Host::from( - format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) - .parse::() - .unwrap(), - )); + let hostname = match url.host_str() { + Some(hostname) => hostname.to_owned(), + _ => panic!() + }; - headers.insert( - header::ACCEPT, - HeaderValue::from_static( - "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8", - ), - ); + headers.set(Host { hostname: hostname, port: url.port() }); - headers.insert( - header::ACCEPT_LANGUAGE, - HeaderValue::from_static("en-US, en; q=0.5"), - ); + let accept = Accept(vec![ + qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), + qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_owned()), vec![])), + QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)), + QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)), + ]); + headers.set(accept); - headers.typed_insert::(crate::DEFAULT_USER_AGENT.parse().unwrap()); + let mut en_us: LanguageTag = Default::default(); + en_us.language = Some("en".to_owned()); + en_us.region = Some("US".to_owned()); + let mut en: LanguageTag = Default::default(); + en.language = Some("en".to_owned()); + headers.set(AcceptLanguage(vec![ + qitem(en_us), + QualityItem::new(en, Quality(500)), + ])); + + headers.set(UserAgent(::DEFAULT_USER_AGENT.to_owned())); *expected_headers.lock().unwrap() = Some(headers.clone()); // Testing for method.GET let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: url.clone().origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); // Testing for method.POST let mut post_headers = headers.clone(); - post_headers.typed_insert(ContentLength(0 as u64)); + post_headers.set(ContentLength(0 as u64)); let url_str = url.as_str(); // request gets header "Origin: http://example.com" but expected_headers has // "Origin: http://example.com/" which do not match for equality so strip trailing '/' - post_headers.insert( - header::ORIGIN, - HeaderValue::from_str(&url_str[..url_str.len() - 1]).unwrap(), - ); + post_headers.set(Origin::from_str(&url_str[..url_str.len()-1]).unwrap()); *expected_headers.lock().unwrap() = Some(post_headers); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::POST, + method: Method::Post, destination: Destination::Document, origin: url.clone().origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let _ = server.close(); } #[test] -fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length_should_be_set_to_0( -) { - let handler = move |request: HyperRequest, _: &mut HyperResponse| { - assert_eq!( - request.headers().typed_get::(), - Some(ContentLength(0)) - ); +fn test_load_when_request_is_not_get_or_head_and_there_is_no_body_content_length_should_be_set_to_0() { + let handler = move |request: HyperRequest, _: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&ContentLength(0))); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::POST, + method: Method::Post, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let _ = server.close(); } #[test] fn test_request_and_response_data_with_network_messages() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response - .headers_mut() - .typed_insert(Host::from("foo.bar".parse::().unwrap())); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(Host { hostname: "foo.bar".to_owned(), port: None }); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); - let mut request_headers = HeaderMap::new(); - request_headers.typed_insert(Host::from("bar.foo".parse::().unwrap())); + let mut request_headers = Headers::new(); + request_headers.set(Host { hostname: "bar.foo".to_owned(), port: None }); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, headers: request_headers, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); let response = fetch(&mut request, Some(devtools_chan)); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let _ = server.close(); @@ -262,37 +224,41 @@ fn test_request_and_response_data_with_network_messages() { let devhttpresponse = expect_devtools_http_response(&devtools_port); //Creating default headers for request - let mut headers = HeaderMap::new(); - - headers.insert( - header::ACCEPT_ENCODING, - HeaderValue::from_static("gzip, deflate, br"), - ); - headers.typed_insert(Host::from( - format!("{}:{}", url.host_str().unwrap(), url.port().unwrap()) - .parse::() - .unwrap(), - )); - - headers.insert( - header::ACCEPT, - HeaderValue::from_static( - "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8", - ), - ); - - headers.insert( - header::ACCEPT_LANGUAGE, - HeaderValue::from_static("en-US, en; q=0.5"), - ); - - headers.typed_insert::(crate::DEFAULT_USER_AGENT.parse().unwrap()); + let mut headers = Headers::new(); + + headers.set(AcceptEncoding(vec![ + qitem(Encoding::Gzip), + qitem(Encoding::Deflate), + qitem(Encoding::EncodingExt("br".to_owned())) + ])); + + headers.set(Host { hostname: url.host_str().unwrap().to_owned() , port: url.port() }); + + let accept = Accept(vec![ + qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), + qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_owned()), vec![])), + QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900u16)), + QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800u16)), + ]); + headers.set(accept); + + let mut en_us: LanguageTag = Default::default(); + en_us.language = Some("en".to_owned()); + en_us.region = Some("US".to_owned()); + let mut en: LanguageTag = Default::default(); + en.language = Some("en".to_owned()); + headers.set(AcceptLanguage(vec![ + qitem(en_us), + QualityItem::new(en, Quality(500)), + ])); + + headers.set(UserAgent(::DEFAULT_USER_AGENT.to_owned())); let httprequest = DevtoolsHttpRequest { url: url, - method: Method::GET, + method: Method::Get, headers: headers, - body: Some(b"".to_vec()), + body: None, pipeline_id: TEST_PIPELINE_ID, startedDateTime: devhttprequest.startedDateTime, timeStamp: devhttprequest.timeStamp, @@ -302,18 +268,10 @@ fn test_request_and_response_data_with_network_messages() { }; let content = "Yay!"; - let mut response_headers = HeaderMap::new(); - response_headers.typed_insert(ContentLength(content.len() as u64)); - response_headers.typed_insert(Host::from("foo.bar".parse::().unwrap())); - response_headers.typed_insert( - devhttpresponse - .headers - .as_ref() - .unwrap() - .typed_get::() - .unwrap() - .clone(), - ); + let mut response_headers = Headers::new(); + response_headers.set(ContentLength(content.len() as u64)); + response_headers.set(Host { hostname: "foo.bar".to_owned(), port: None }); + response_headers.set(devhttpresponse.headers.as_ref().unwrap().get::().unwrap().clone()); let httpresponse = DevtoolsHttpResponse { headers: Some(response_headers), @@ -328,33 +286,23 @@ fn test_request_and_response_data_with_network_messages() { #[test] fn test_request_and_response_message_from_devtool_without_pipeline_id() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response - .headers_mut() - .typed_insert(Host::from("foo.bar".parse::().unwrap())); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(Host { hostname: "foo.bar".to_owned(), port: None }); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: None, - ..RequestInit::default() + .. RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); let response = fetch(&mut request, Some(devtools_chan)); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let _ = server.close(); @@ -364,29 +312,27 @@ fn test_request_and_response_message_from_devtool_without_pipeline_id() { #[test] fn test_redirected_request_to_devtools() { - let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::GET); - *response.body_mut() = b"Yay!".to_vec().into(); + let post_handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.method, Method::Get); + response.send(b"Yay!").unwrap(); }; - let (post_server, post_url) = make_server(post_handler); + let (mut post_server, post_url) = make_server(post_handler); let post_redirect_url = post_url.clone(); - let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::POST); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let pre_handler = move |request: HyperRequest, mut response: HyperResponse| { + assert_eq!(request.method, Method::Post); + response.headers_mut().set(Location(post_redirect_url.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (pre_server, pre_url) = make_server(pre_handler); + let (mut pre_server, pre_url) = make_server(pre_handler); let mut request = Request::from_init(RequestInit { url: pre_url.clone(), - method: Method::POST, + method: Method::Post, destination: Destination::Document, pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let (devtools_chan, devtools_port) = channel(); fetch(&mut request, Some(devtools_chan)); @@ -397,231 +343,183 @@ fn test_redirected_request_to_devtools() { let devhttprequest = expect_devtools_http_request(&devtools_port); let devhttpresponse = expect_devtools_http_response(&devtools_port); - assert_eq!(devhttprequest.method, Method::POST); + assert_eq!(devhttprequest.method, Method::Post); assert_eq!(devhttprequest.url, pre_url); - assert_eq!( - devhttpresponse.status, - Some((301, b"Moved Permanently".to_vec())) - ); + assert_eq!(devhttpresponse.status, Some((301, b"Moved Permanently".to_vec()))); let devhttprequest = expect_devtools_http_request(&devtools_port); let devhttpresponse = expect_devtools_http_response(&devtools_port); - assert_eq!(devhttprequest.method, Method::GET); + assert_eq!(devhttprequest.method, Method::Get); assert_eq!(devhttprequest.url, post_url); assert_eq!(devhttpresponse.status, Some((200, b"OK".to_vec()))); } + + #[test] fn test_load_when_redirecting_from_a_post_should_rewrite_next_request_as_get() { - let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::GET); - *response.body_mut() = b"Yay!".to_vec().into(); + let post_handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.method, Method::Get); + response.send(b"Yay!").unwrap(); }; - let (post_server, post_url) = make_server(post_handler); + let (mut post_server, post_url) = make_server(post_handler); let post_redirect_url = post_url.clone(); - let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::POST); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let pre_handler = move |request: HyperRequest, mut response: HyperResponse| { + assert_eq!(request.method, Method::Post); + response.headers_mut().set(Location(post_redirect_url.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (pre_server, pre_url) = make_server(pre_handler); + let (mut pre_server, pre_url) = make_server(pre_handler); let mut request = Request::from_init(RequestInit { url: pre_url.clone(), - method: Method::POST, + method: Method::Post, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = pre_server.close(); let _ = post_server.close(); - assert!(response.to_actual().status.unwrap().0.is_success()); + assert!(response.to_actual().status.unwrap().is_success()); } #[test] -fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_content_encoding_deflate( -) { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::CONTENT_ENCODING, - HeaderValue::from_static("deflate"), - ); +fn test_load_should_decode_the_response_as_deflate_when_response_headers_have_content_encoding_deflate() { + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(ContentEncoding(vec![Encoding::Deflate])); let mut e = DeflateEncoder::new(Vec::new(), Compression::default()); e.write(b"Yay!").unwrap(); let encoded_content = e.finish().unwrap(); - *response.body_mut() = encoded_content.into(); + response.send(&encoded_content).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); let internal_response = response.internal_response.unwrap(); - assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!( - *internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec()) - ); + assert!(internal_response.status.unwrap().is_success()); + assert_eq!(*internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec())); } #[test] fn test_load_should_decode_the_response_as_gzip_when_response_headers_have_content_encoding_gzip() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response - .headers_mut() - .insert(header::CONTENT_ENCODING, HeaderValue::from_static("gzip")); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(ContentEncoding(vec![Encoding::Gzip])); let mut e = GzEncoder::new(Vec::new(), Compression::default()); e.write(b"Yay!").unwrap(); let encoded_content = e.finish().unwrap(); - *response.body_mut() = encoded_content.into(); + response.send(&encoded_content).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); let internal_response = response.internal_response.unwrap(); - assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!( - *internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec()) - ); + assert!(internal_response.status.unwrap().is_success()); + assert_eq!(*internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec())); } #[test] fn test_load_doesnt_send_request_body_on_any_redirect() { - let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::GET); - read_response(request) - .and_then(|data| { - assert_eq!(data, ""); - futures::future::ok(()) - }) - .poll() - .unwrap(); - *response.body_mut() = b"Yay!".to_vec().into(); + let post_handler = move |mut request: HyperRequest, response: HyperResponse| { + assert_eq!(request.method, Method::Get); + let data = read_response(&mut request); + assert_eq!(data, ""); + response.send(b"Yay!").unwrap(); }; - let (post_server, post_url) = make_server(post_handler); + let (mut post_server, post_url) = make_server(post_handler); let post_redirect_url = post_url.clone(); - let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { - read_response(request) - .and_then(|data| { - assert_eq!(data, "Body on POST"); - futures::future::ok(()) - }) - .poll() - .unwrap(); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let pre_handler = move |mut request: HyperRequest, mut response: HyperResponse| { + let data = read_response(&mut request); + assert_eq!(data, "Body on POST!"); + response.headers_mut().set(Location(post_redirect_url.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (pre_server, pre_url) = make_server(pre_handler); + let (mut pre_server, pre_url) = make_server(pre_handler); let mut request = Request::from_init(RequestInit { url: pre_url.clone(), body: Some(b"Body on POST!".to_vec()), - method: Method::POST, + method: Method::Post, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = pre_server.close(); let _ = post_server.close(); - assert!(response.to_actual().status.unwrap().0.is_success()); + assert!(response.to_actual().status.unwrap().is_success()); } #[test] fn test_load_doesnt_add_host_to_sts_list_when_url_is_http_even_if_sts_headers_are_present() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response - .headers_mut() - .typed_insert(StrictTransportSecurity::excluding_subdomains( - Duration::from_secs(31536000), - )); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(StrictTransportSecurity::excluding_subdomains(31536000)); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let context = new_fetch_context(None, None); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); - assert_eq!( - context - .state - .hsts_list - .read() - .unwrap() - .is_host_secure(url.host_str().unwrap()), - false - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); + assert_eq!(context.state.hsts_list.read().unwrap().is_host_secure(url.host_str().unwrap()), false); } #[test] fn test_load_sets_cookies_in_the_resource_manager_when_it_get_set_cookie_header_in_response() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_static("mozillaIs=theBest"), - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(SetCookie(vec!["mozillaIs=theBest".to_owned()])); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let context = new_fetch_context(None, None); @@ -629,45 +527,31 @@ fn test_load_sets_cookies_in_the_resource_manager_when_it_get_set_cookie_header_ let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); - - assert_cookie_for_domain( - &context.state.cookie_jar, - url.as_str(), - Some("mozillaIs=theBest"), - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); + + assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), Some("mozillaIs=theBest")); } #[test] fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_resource_manager() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request.headers().get(header::COOKIE).unwrap().as_bytes(), - b"mozillaIs=theBest" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), + Some(&CookieHeader(vec!["mozillaIs=theBest".to_owned()]))); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let context = new_fetch_context(None, None); @@ -676,47 +560,36 @@ fn test_load_sets_requests_cookies_header_for_url_by_getting_cookies_from_the_re let cookie = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url, - CookieSource::HTTP, - ) - .unwrap(); + CookieSource::HTTP + ).unwrap(); cookie_jar.push(cookie, &url, CookieSource::HTTP); } let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_sends_cookie_if_nonhttp() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request.headers().get(header::COOKIE).unwrap().as_bytes(), - b"mozillaIs=theBest" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), + Some(&CookieHeader(vec!["mozillaIs=theBest".to_owned()]))); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let context = new_fetch_context(None, None); @@ -725,47 +598,36 @@ fn test_load_sends_cookie_if_nonhttp() { let cookie = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url, - CookieSource::NonHTTP, - ) - .unwrap(); + CookieSource::NonHTTP + ).unwrap(); cookie_jar.push(cookie, &url, CookieSource::HTTP); } let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_static("mozillaIs=theBest; HttpOnly"), - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + let pair = vec!["mozillaIs=theBest; HttpOnly".to_owned()]; + response.headers_mut().set(SetCookie(pair)); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let context = new_fetch_context(None, None); @@ -773,51 +635,33 @@ fn test_cookie_set_with_httponly_should_not_be_available_using_getcookiesforurl( let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); - - assert_cookie_for_domain( - &context.state.cookie_jar, - url.as_str(), - Some("mozillaIs=theBest"), - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); + + assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), Some("mozillaIs=theBest")); let mut cookie_jar = context.state.cookie_jar.write().unwrap(); - assert!( - cookie_jar - .cookies_for_url(&url, CookieSource::NonHTTP) - .is_none() - ); + assert!(cookie_jar.cookies_for_url(&url, CookieSource::NonHTTP).is_none()); } #[test] fn test_when_cookie_received_marked_secure_is_ignored_for_http() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_static("mozillaIs=theBest; Secure"), - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |_: HyperRequest, mut response: HyperResponse| { + let pair = vec!["mozillaIs=theBest; Secure".to_owned()]; + response.headers_mut().set(SetCookie(pair)); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let context = new_fetch_context(None, None); @@ -825,27 +669,19 @@ fn test_when_cookie_received_marked_secure_is_ignored_for_http() { let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); assert_cookie_for_domain(&context.state.cookie_jar, url.as_str(), None); } @@ -853,252 +689,176 @@ fn test_when_cookie_received_marked_secure_is_ignored_for_http() { #[test] fn test_load_sets_content_length_to_length_of_request_body() { let content = b"This is a request body"; - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let content_length = ContentLength(content.len() as u64); - assert_eq!( - request.headers().typed_get::(), - Some(content_length) - ); - *response.body_mut() = content.to_vec().into(); + let content_length = ContentLength(content.len() as u64); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&content_length)); + response.send(content).unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::POST, + method: Method::Post, body: Some(content.to_vec()), destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_uses_explicit_accept_from_headers_in_load_data() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request - .headers() - .get(header::ACCEPT) - .unwrap() - .to_str() - .unwrap(), - "text/html" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let accept = Accept(vec![qitem(Mime(TopLevel::Text, SubLevel::Html, vec![]))]); + let expected_accept = accept.clone(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&expected_accept)); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); - let mut accept_headers = HeaderMap::new(); - accept_headers.insert(header::ACCEPT, HeaderValue::from_static("text/html")); + let mut accept_headers = Headers::new(); + accept_headers.set(accept); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, headers: accept_headers, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_sets_default_accept_to_html_xhtml_xml_and_then_anything_else() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request - .headers() - .get(header::ACCEPT) - .unwrap() - .to_str() - .unwrap(), - "text/html, application/xhtml+xml, application/xml; q=0.9, */*; q=0.8" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&Accept(vec![ + qitem(Mime(TopLevel::Text, SubLevel::Html, vec![])), + qitem(Mime(TopLevel::Application, SubLevel::Ext("xhtml+xml".to_owned()), vec![])), + QualityItem::new(Mime(TopLevel::Application, SubLevel::Xml, vec![]), Quality(900)), + QualityItem::new(Mime(TopLevel::Star, SubLevel::Star, vec![]), Quality(800)), + ]))); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_uses_explicit_accept_encoding_from_load_data_headers() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request - .headers() - .get(header::ACCEPT_ENCODING) - .unwrap() - .to_str() - .unwrap(), - "chunked" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let accept_encoding = AcceptEncoding(vec![qitem(Encoding::Chunked)]); + let expected_accept_encoding = accept_encoding.clone(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&expected_accept_encoding)); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); - let mut accept_encoding_headers = HeaderMap::new(); - accept_encoding_headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("chunked")); + let mut accept_encoding_headers = Headers::new(); + accept_encoding_headers.set(accept_encoding); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, headers: accept_encoding_headers, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_sets_default_accept_encoding_to_gzip_and_deflate() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!( - request - .headers() - .get(header::ACCEPT_ENCODING) - .unwrap() - .to_str() - .unwrap(), - "gzip, deflate, br" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + let handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.headers.get::(), Some(&AcceptEncoding(vec![ + qitem(Encoding::Gzip), + qitem(Encoding::Deflate), + qitem(Encoding::EncodingExt("br".to_owned())) + ]))); + response.send(b"Yay!").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_load_errors_when_there_a_redirect_loop() { let url_b_for_a = Arc::new(Mutex::new(None::)); let url_b_for_a_clone = url_b_for_a.clone(); - let handler_a = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str( - &url_b_for_a_clone - .lock() - .unwrap() - .as_ref() - .unwrap() - .to_string(), - ) - .unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let handler_a = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(Location(url_b_for_a_clone.lock().unwrap().as_ref().unwrap().to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (server_a, url_a) = make_server(handler_a); + let (mut server_a, url_a) = make_server(handler_a); let url_a_for_b = url_a.clone(); - let handler_b = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&url_a_for_b.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let handler_b = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(Location(url_a_for_b.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (server_b, url_b) = make_server(handler_b); + let (mut server_b, url_b) = make_server(handler_b); *url_b_for_a.lock().unwrap() = Some(url_b.clone()); let mut request = Request::from_init(RequestInit { url: url_a.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server_a.close(); let _ = server_b.close(); - assert_eq!( - response.get_network_error(), - Some(&NetworkError::Internal("Too many redirects".to_owned())) - ); + assert_eq!(response.get_network_error(), + Some(&NetworkError::Internal("Too many redirects".to_owned()))); } #[test] @@ -1106,46 +866,34 @@ fn test_load_succeeds_with_a_redirect_loop() { let url_b_for_a = Arc::new(Mutex::new(None::)); let url_b_for_a_clone = url_b_for_a.clone(); let handled_a = AtomicBool::new(false); - let handler_a = move |_: HyperRequest, response: &mut HyperResponse| { + let handler_a = move |_: HyperRequest, mut response: HyperResponse| { if !handled_a.swap(true, Ordering::SeqCst) { - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str( - &url_b_for_a_clone - .lock() - .unwrap() - .as_ref() - .unwrap() - .to_string(), - ) - .unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + response.headers_mut().set(Location(url_b_for_a_clone.lock().unwrap().as_ref().unwrap().to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); } else { - *response.body_mut() = b"Success".to_vec().into() + response.send(b"Success").unwrap(); } }; - let (server_a, url_a) = make_server(handler_a); + let (mut server_a, url_a) = make_server(handler_a); let url_a_for_b = url_a.clone(); - let handler_b = move |_: HyperRequest, response: &mut HyperResponse| { - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&url_a_for_b.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let handler_b = move |_: HyperRequest, mut response: HyperResponse| { + response.headers_mut().set(Location(url_a_for_b.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (server_b, url_b) = make_server(handler_b); + let (mut server_b, url_b) = make_server(handler_b); *url_b_for_a.lock().unwrap() = Some(url_b.clone()); let mut request = Request::from_init(RequestInit { url: url_a.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); @@ -1154,38 +902,34 @@ fn test_load_succeeds_with_a_redirect_loop() { let response = response.to_actual(); assert_eq!(response.url_list, [url_a.clone(), url_b, url_a]); - assert_eq!( - *response.body.lock().unwrap(), - ResponseBody::Done(b"Success".to_vec()) - ); + assert_eq!(*response.body.lock().unwrap(), + ResponseBody::Done(b"Success".to_vec())); } #[test] fn test_load_follows_a_redirect() { - let post_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::GET); - *response.body_mut() = b"Yay!".to_vec().into(); + let post_handler = move |request: HyperRequest, response: HyperResponse| { + assert_eq!(request.method, Method::Get); + response.send(b"Yay!").unwrap(); }; - let (post_server, post_url) = make_server(post_handler); + let (mut post_server, post_url) = make_server(post_handler); let post_redirect_url = post_url.clone(); - let pre_handler = move |request: HyperRequest, response: &mut HyperResponse| { - assert_eq!(request.method(), Method::GET); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&post_redirect_url.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + let pre_handler = move |request: HyperRequest, mut response: HyperResponse| { + assert_eq!(request.method, Method::Get); + response.headers_mut().set(Location(post_redirect_url.to_string())); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); }; - let (pre_server, pre_url) = make_server(pre_handler); + let (mut pre_server, pre_url) = make_server(pre_handler); let mut request = Request::from_init(RequestInit { url: pre_url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); @@ -1193,41 +937,36 @@ fn test_load_follows_a_redirect() { let _ = post_server.close(); let internal_response = response.internal_response.unwrap(); - assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!( - *internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec()) - ); + assert!(internal_response.status.unwrap().is_success()); + assert_eq!(*internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec())); } #[test] fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { let shared_url_y = Arc::new(Mutex::new(None::)); let shared_url_y_clone = shared_url_y.clone(); - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let path = request.uri().path(); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let path = match request.uri { + RequestUri::AbsolutePath(path) => path, + uri => panic!("Unexpected uri: {:?}", uri), + }; if path == "/com/" { - assert_eq!( - request.headers().get(header::COOKIE).unwrap().as_bytes(), - b"mozillaIsNot=dotOrg" - ); + assert_eq!(request.headers.get(), + Some(&CookieHeader(vec!["mozillaIsNot=dotOrg".to_owned()]))); let location = shared_url_y.lock().unwrap().as_ref().unwrap().to_string(); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&location.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + response.headers_mut().set(Location(location)); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); } else if path == "/org/" { - assert_eq!( - request.headers().get(header::COOKIE).unwrap().as_bytes(), - b"mozillaIs=theBest" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + assert_eq!(request.headers.get(), + Some(&CookieHeader(vec!["mozillaIs=theBest".to_owned()]))); + response.send(b"Yay!").unwrap(); } else { panic!("unexpected path {:?}", path) } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let port = url.port().unwrap(); assert_eq!(url.host_str(), Some("localhost")); @@ -1248,112 +987,103 @@ fn test_redirect_from_x_to_y_provides_y_cookies_from_y() { let cookie_x = Cookie::new_wrapped( CookiePair::new("mozillaIsNot".to_owned(), "dotOrg".to_owned()), &url_x, - CookieSource::HTTP, - ) - .unwrap(); + CookieSource::HTTP + ).unwrap(); cookie_jar.push(cookie_x, &url_x, CookieSource::HTTP); let cookie_y = Cookie::new_wrapped( CookiePair::new("mozillaIs".to_owned(), "theBest".to_owned()), &url_y, - CookieSource::HTTP, - ) - .unwrap(); + CookieSource::HTTP + ).unwrap(); cookie_jar.push(cookie_y, &url_y, CookieSource::HTTP); } let mut request = Request::from_init(RequestInit { url: url_x.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch_with_context(&mut request, &context); let _ = server.close(); let internal_response = response.internal_response.unwrap(); - assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!( - *internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec()) - ); + assert!(internal_response.status.unwrap().is_success()); + assert_eq!(*internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec())); } #[test] fn test_redirect_from_x_to_x_provides_x_with_cookie_from_first_response() { - let handler = move |request: HyperRequest, response: &mut HyperResponse| { - let path = request.uri().path(); + let handler = move |request: HyperRequest, mut response: HyperResponse| { + let path = match request.uri { + ::hyper::uri::RequestUri::AbsolutePath(path) => path, + uri => panic!("Unexpected uri: {:?}", uri), + }; if path == "/initial/" { - response.headers_mut().insert( - header::SET_COOKIE, - HeaderValue::from_static("mozillaIs=theBest; path=/;"), - ); + response.headers_mut().set_raw("set-cookie", vec![b"mozillaIs=theBest; path=/;".to_vec()]); let location = "/subsequent/".to_string(); - response.headers_mut().insert( - header::LOCATION, - HeaderValue::from_str(&location.to_string()).unwrap(), - ); - *response.status_mut() = StatusCode::MOVED_PERMANENTLY; + response.headers_mut().set(Location(location)); + *response.status_mut() = StatusCode::MovedPermanently; + response.send(b"").unwrap(); } else if path == "/subsequent/" { - assert_eq!( - request.headers().get(header::COOKIE).unwrap().as_bytes(), - b"mozillaIs=theBest" - ); - *response.body_mut() = b"Yay!".to_vec().into(); + assert_eq!(request.headers.get(), + Some(&CookieHeader(vec!["mozillaIs=theBest".to_owned()]))); + response.send(b"Yay!").unwrap(); } else { panic!("unexpected path {:?}", path) } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let url = url.join("/initial/").unwrap(); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); let internal_response = response.internal_response.unwrap(); - assert!(internal_response.status.clone().unwrap().0.is_success()); - assert_eq!( - *internal_response.body.lock().unwrap(), - ResponseBody::Done(b"Yay!".to_vec()) - ); + assert!(internal_response.status.unwrap().is_success()); + assert_eq!(*internal_response.body.lock().unwrap(), + ResponseBody::Done(b"Yay!".to_vec())); } #[test] fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { - let handler = move |request: HyperRequest, _response: &mut HyperResponse| { - let expected = Authorization::basic("username", "test"); - assert_eq!( - request.headers().typed_get::>(), - Some(expected) - ); + let handler = move |request: HyperRequest, response: HyperResponse| { + let expected = Authorization(Basic { + username: "username".to_owned(), + password: Some("test".to_owned()) + }); + assert_eq!(request.headers.get(), Some(&expected)); + response.send(b"").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let context = new_fetch_context(None, None); @@ -1362,143 +1092,95 @@ fn test_if_auth_creds_not_in_url_but_in_cache_it_sets_it() { password: "test".to_owned(), }; - context - .state - .auth_cache - .write() - .unwrap() - .entries - .insert(url.origin().clone().ascii_serialization(), auth_entry); + context.state.auth_cache.write().unwrap().entries.insert(url.origin().clone().ascii_serialization(), auth_entry); let response = fetch_with_context(&mut request, &context); let _ = server.close(); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); } #[test] fn test_auth_ui_needs_www_auth() { - let handler = move |_: HyperRequest, response: &mut HyperResponse| { - *response.status_mut() = StatusCode::UNAUTHORIZED; + let handler = move |_: HyperRequest, mut response: HyperResponse| { + *response.status_mut() = StatusCode::Unauthorized; + response.send(b"").unwrap(); }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, body: None, destination: Destination::Document, origin: mock_origin(), pipeline_id: Some(TEST_PIPELINE_ID), credentials_mode: CredentialsMode::Include, - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); let _ = server.close(); - assert_eq!( - response.internal_response.unwrap().status.unwrap().0, - StatusCode::UNAUTHORIZED - ); + assert_eq!(response.internal_response.unwrap().status.unwrap(), StatusCode::Unauthorized); } #[test] fn test_origin_set() { let origin_header = Arc::new(Mutex::new(None)); let origin_header_clone = origin_header.clone(); - let handler = move |request: HyperRequest, resp: &mut HyperResponse| { + let handler = move |request: HyperRequest, mut resp: HyperResponse| { let origin_header_clone = origin_header.clone(); - resp.headers_mut() - .typed_insert(AccessControlAllowOrigin::ANY); - match request.headers().typed_get::() { + resp.headers_mut().set(AccessControlAllowOrigin::Any); + match request.headers.get::() { None => assert_eq!(origin_header_clone.lock().unwrap().take(), None), - Some(h) => assert_eq!(h, origin_header_clone.lock().unwrap().take().unwrap()), + Some(h) => assert_eq!(*h, origin_header_clone.lock().unwrap().take().unwrap()), } }; - let (server, url) = make_server(handler); + let (mut server, url) = make_server(handler); - let mut origin = - Origin::try_from_parts(url.scheme(), url.host_str().unwrap(), url.port()).unwrap(); + let mut origin = Origin::new(url.scheme(), url.host_str().unwrap(), url.port()); *origin_header_clone.lock().unwrap() = Some(origin.clone()); let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::POST, + method: Method::Post, body: None, origin: url.clone().origin(), - ..RequestInit::default() + .. RequestInit::default() }); let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let origin_url = ServoUrl::parse("http://example.com").unwrap(); - // XXX: Not sure about the Some(80) here. origin_url.origin() returns 80 for the port but origin_url returns None. - origin = Origin::try_from_parts( - origin_url.scheme(), - origin_url.host_str().unwrap(), - Some(80), - ) - .unwrap(); + origin = Origin::new(origin_url.scheme(), origin_url.host_str().unwrap(), origin_url.port()); // Test Origin header is set on Get request with CORS mode let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::GET, + method: Method::Get, mode: RequestMode::CorsMode, body: None, origin: origin_url.clone().origin(), - ..RequestInit::default() + .. RequestInit::default() }); *origin_header_clone.lock().unwrap() = Some(origin.clone()); let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); // Test Origin header is not set on method Head let mut request = Request::from_init(RequestInit { url: url.clone(), - method: Method::HEAD, + method: Method::Head, body: None, origin: url.clone().origin(), - ..RequestInit::default() + .. RequestInit::default() }); *origin_header_clone.lock().unwrap() = None; let response = fetch(&mut request, None); - assert!( - response - .internal_response - .unwrap() - .status - .unwrap() - .0 - .is_success() - ); + assert!(response.internal_response.unwrap().status.unwrap().is_success()); let _ = server.close(); } diff --git a/components/net/tests/main.rs b/components/net/tests/main.rs index 48063adad811..aeddb5105d12 100644 --- a/components/net/tests/main.rs +++ b/components/net/tests/main.rs @@ -4,8 +4,24 @@ #![cfg(test)] -#[macro_use] -extern crate lazy_static; +extern crate cookie as cookie_rs; +extern crate devtools_traits; +extern crate embedder_traits; +extern crate flate2; +extern crate hyper; +extern crate hyper_openssl; +extern crate hyper_serde; +extern crate ipc_channel; +extern crate msg; +extern crate net; +extern crate net_traits; +extern crate profile_traits; +extern crate servo_channel; +extern crate servo_config; +extern crate servo_url; +extern crate time; +extern crate unicase; +extern crate url; mod cookie; mod cookie_http_state; @@ -20,34 +36,20 @@ mod resource_thread; mod subresource_integrity; use devtools_traits::DevtoolsControlMsg; -use embedder_traits::resources::{self, Resource}; use embedder_traits::{EmbedderProxy, EventLoopWaker}; -use futures::{Future, Stream}; -use hyper::server::conn::Http; -use hyper::server::Server as HyperServer; -use hyper::service::service_fn_ok; -use hyper::{Body, Request as HyperRequest, Response as HyperResponse}; -use net::connector::create_ssl_connector_builder; +use embedder_traits::resources::{self, Resource}; +use hyper::server::{Handler, Listening, Server}; +use net::connector::create_ssl_client; use net::fetch::cors_cache::CorsCache; use net::fetch::methods::{self, CancellationListener, FetchContext}; use net::filemanager_thread::FileManager; use net::test::HttpState; +use net_traits::FetchTaskTarget; use net_traits::request::Request; use net_traits::response::Response; -use net_traits::FetchTaskTarget; -use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod}; use servo_channel::{channel, Sender}; use servo_url::ServoUrl; -use std::net::TcpListener as StdTcpListener; -use std::path::PathBuf; use std::sync::{Arc, Mutex}; -use tokio::net::TcpListener; -use tokio::runtime::Runtime; -use tokio_openssl::SslAcceptorExt; - -lazy_static! { - pub static ref HANDLE: Mutex = { Mutex::new(Runtime::new().unwrap()) }; -} const DEFAULT_USER_AGENT: &'static str = "Such Browser. Very Layout. Wow."; @@ -57,17 +59,18 @@ struct FetchResponseCollector { fn create_embedder_proxy() -> EmbedderProxy { let (sender, _) = channel(); - let event_loop_waker = || { - struct DummyEventLoopWaker {} + let event_loop_waker = | | { + struct DummyEventLoopWaker { + } impl DummyEventLoopWaker { fn new() -> DummyEventLoopWaker { - DummyEventLoopWaker {} + DummyEventLoopWaker { } } } impl EventLoopWaker for DummyEventLoopWaker { - fn wake(&self) {} - fn clone(&self) -> Box { - Box::new(DummyEventLoopWaker {}) + fn wake(&self) { } + fn clone(&self) -> Box { + Box::new(DummyEventLoopWaker { }) } } @@ -76,19 +79,15 @@ fn create_embedder_proxy() -> EmbedderProxy { EmbedderProxy { sender: sender, - event_loop_waker: event_loop_waker(), + event_loop_waker: event_loop_waker() } } -fn new_fetch_context( - dc: Option>, - fc: Option, -) -> FetchContext { - let ssl_connector = - create_ssl_connector_builder(&resources::read_string(Resource::SSLCertificates)); +fn new_fetch_context(dc: Option>, fc: Option) -> FetchContext { + let ssl_client = create_ssl_client(&resources::read_string(Resource::SSLCertificates)); let sender = fc.unwrap_or_else(|| create_embedder_proxy()); FetchContext { - state: Arc::new(HttpState::new(ssl_connector)), + state: Arc::new(HttpState::new(ssl_client)), user_agent: DEFAULT_USER_AGENT.into(), devtools_chan: dc, filemanager: FileManager::new(sender), @@ -112,7 +111,9 @@ fn fetch(request: &mut Request, dc: Option>) -> Respo fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response { let (sender, receiver) = channel(); - let mut target = FetchResponseCollector { sender: sender }; + let mut target = FetchResponseCollector { + sender: sender, + }; methods::fetch(request, &mut target, context); @@ -121,96 +122,19 @@ fn fetch_with_context(request: &mut Request, context: &FetchContext) -> Response fn fetch_with_cors_cache(request: &mut Request, cache: &mut CorsCache) -> Response { let (sender, receiver) = channel(); - let mut target = FetchResponseCollector { sender: sender }; + let mut target = FetchResponseCollector { + sender: sender, + }; methods::fetch_with_cors_cache(request, cache, &mut target, &new_fetch_context(None, None)); receiver.recv().unwrap() } -pub(crate) struct Server { - pub close_channel: futures::sync::oneshot::Sender<()>, -} - -impl Server { - fn close(self) { - self.close_channel.send(()).unwrap(); - } -} - -fn make_server(handler: H) -> (Server, ServoUrl) -where - H: Fn(HyperRequest, &mut HyperResponse) + Send + Sync + 'static, -{ - let handler = Arc::new(handler); - let listener = StdTcpListener::bind("0.0.0.0:0").unwrap(); - let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); +fn make_server(handler: H) -> (Listening, ServoUrl) { + // this is a Listening server because of handle_threads() + let server = Server::http("0.0.0.0:0").unwrap().handle_threads(handler, 2).unwrap(); + let url_string = format!("http://localhost:{}", server.socket.port()); let url = ServoUrl::parse(&url_string).unwrap(); - let (tx, rx) = futures::sync::oneshot::channel::<()>(); - let server = HyperServer::from_tcp(listener) - .unwrap() - .serve(move || { - let handler = handler.clone(); - service_fn_ok(move |req: HyperRequest| { - let mut response = HyperResponse::new(Vec::::new().into()); - handler(req, &mut response); - response - }) - }) - .with_graceful_shutdown(rx) - .map_err(|_| ()); - - HANDLE.lock().unwrap().spawn(server); - let server = Server { close_channel: tx }; - (server, url) -} - -fn make_ssl_server(handler: H, cert_path: PathBuf, key_path: PathBuf) -> (Server, ServoUrl) -where - H: Fn(HyperRequest, &mut HyperResponse) + Send + Sync + 'static, -{ - let handler = Arc::new(handler); - let listener = StdTcpListener::bind("[::0]:0").unwrap(); - let listener = TcpListener::from_std(listener, &HANDLE.lock().unwrap().reactor()).unwrap(); - let url_string = format!("http://localhost:{}", listener.local_addr().unwrap().port()); - let url = ServoUrl::parse(&url_string).unwrap(); - - let server = listener.incoming().map_err(|_| ()).for_each(move |sock| { - let mut ssl_builder = SslAcceptor::mozilla_modern(SslMethod::tls()).unwrap(); - ssl_builder - .set_certificate_file(&cert_path, SslFiletype::PEM) - .unwrap(); - ssl_builder - .set_private_key_file(&key_path, SslFiletype::PEM) - .unwrap(); - - let handler = handler.clone(); - ssl_builder - .build() - .accept_async(sock) - .map_err(|_| ()) - .and_then(move |ssl| { - Http::new() - .serve_connection( - ssl, - service_fn_ok(move |req: HyperRequest| { - let mut response = HyperResponse::new(Vec::::new().into()); - handler(req, &mut response); - response - }), - ) - .map_err(|_| ()) - }) - }); - - let (tx, rx) = futures::sync::oneshot::channel::<()>(); - let server = server - .select(rx.map_err(|_| ())) - .map(|_| ()) - .map_err(|_| ()); - - HANDLE.lock().unwrap().spawn(server); - - let server = Server { close_channel: tx }; (server, url) } diff --git a/components/net/tests/mime_classifier.rs b/components/net/tests/mime_classifier.rs index d2568a9a8be4..1a4757ded5f2 100644 --- a/components/net/tests/mime_classifier.rs +++ b/components/net/tests/mime_classifier.rs @@ -2,8 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use mime::{self, Mime}; use net::mime_classifier::{ApacheBugFlag, MimeClassifier, Mp4Matcher, NoSniffFlag}; +use net::mime_classifier::as_string_option; use net_traits::LoadContext; use std::env; use std::fs::File; @@ -33,7 +33,7 @@ fn test_sniff_mp4_matcher() { panic!("Didn't read mime type") } }, - Err(e) => panic!("Couldn't read from file with error {}", e), + Err(e) => panic!("Couldn't read from file with error {}", e) } } @@ -43,9 +43,9 @@ fn test_sniff_mp4_matcher_long() { let matcher = Mp4Matcher; let mut data: [u8; 260] = [0; 260]; - &data[..11].clone_from_slice(&[ - 0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34, - ]); + &data[.. 11].clone_from_slice( + &[0x00, 0x00, 0x01, 0x04, 0x66, 0x74, 0x79, 0x70, 0x6D, 0x70, 0x34] + ); assert!(matcher.matches(&data)); } @@ -57,18 +57,14 @@ fn test_validate_classifier() { } #[cfg(test)] -fn test_sniff_with_flags( - filename_orig: &path::Path, - expected_mime: Mime, - supplied_type: Option, - no_sniff_flag: NoSniffFlag, - apache_bug_flag: ApacheBugFlag, -) { +fn test_sniff_with_flags(filename_orig: &path::Path, + type_string: &str, + subtype_string: &str, + supplied_type: Option<(&'static str, &'static str)>, + no_sniff_flag: NoSniffFlag, + apache_bug_flag: ApacheBugFlag) { let current_working_directory = env::current_dir().unwrap(); - println!( - "The current directory is {}", - current_working_directory.display() - ); + println!("The current directory is {}", current_working_directory.display()); let mut filename = PathBuf::from("tests/parsable_mime/"); filename.push(filename_orig); @@ -79,549 +75,486 @@ fn test_sniff_with_flags( match read_result { Ok(data) => { - let parsed_mime = classifier.classify( - LoadContext::Browsing, - no_sniff_flag, - apache_bug_flag, - &supplied_type, - &data, - ); - if (parsed_mime.type_() != expected_mime.type_()) || - (parsed_mime.subtype() != expected_mime.subtype()) - { - panic!( - "File {:?} parsed incorrectly should be {:?}, parsed as {:?}", - filename, expected_mime, parsed_mime - ); + let supplied_type = supplied_type.map(|(x, y)| (x.parse().unwrap(), y)); + let (parsed_type, parsed_subtp) = classifier.classify(LoadContext::Browsing, + no_sniff_flag, + apache_bug_flag, + &as_string_option(supplied_type), + &data); + if (&parsed_type[..] != type_string) || + (&parsed_subtp[..] != subtype_string) { + panic!("File {:?} parsed incorrectly should be {}/{}, parsed as {}/{}", + filename, type_string, subtype_string, + parsed_type, parsed_subtp); } - }, - Err(e) => panic!("Couldn't read from file {:?} with error {}", filename, e), + } + Err(e) => panic!("Couldn't read from file {:?} with error {}", + filename, e), } } #[cfg(test)] -fn test_sniff_full(filename_orig: &path::Path, expected_mime: Mime, supplied_type: Option) { - test_sniff_with_flags( - filename_orig, - expected_mime, - supplied_type, - NoSniffFlag::Off, - ApacheBugFlag::Off, - ) +fn test_sniff_full(filename_orig: &path::Path, type_string: &str, subtype_string: &str, + supplied_type: Option<(&'static str, &'static str)>) { + test_sniff_with_flags(filename_orig, + type_string, + subtype_string, + supplied_type, + NoSniffFlag::Off, + ApacheBugFlag::Off) } #[cfg(test)] -fn test_sniff_classification(file: &str, expected_mime: Mime, supplied_type: Option) { +fn test_sniff_classification(file: &str, type_string: &str, subtype_string: &str, + supplied_type: Option<(&'static str, &'static str)>) { let mut x = PathBuf::from("./"); - x.push(expected_mime.type_().as_str()); - x.push(expected_mime.subtype().as_str()); + x.push(type_string); + x.push(subtype_string); x.push(file); - test_sniff_full(&x, expected_mime, supplied_type); + test_sniff_full(&x, type_string, subtype_string, supplied_type); } #[cfg(test)] -fn test_sniff_classification_sup(file: &str, expected_mime: Mime) { - test_sniff_classification(file, expected_mime.clone(), None); - let no_sub = format!("{}/", expected_mime.type_()).parse().unwrap(); - test_sniff_classification(file, expected_mime, Some(no_sub)); +fn test_sniff_classification_sup(file: &str, type_string: &'static str, subtype_string: &str) { + test_sniff_classification(file, type_string, subtype_string, None); + let class_type = Some((type_string, "")); + test_sniff_classification(file, type_string, subtype_string, class_type); } #[test] fn test_sniff_x_icon() { - test_sniff_classification_sup("test.ico", "image/x-icon".parse().unwrap()); + test_sniff_classification_sup("test.ico", "image", "x-icon"); } #[test] fn test_sniff_x_icon_cursor() { - test_sniff_classification_sup("test_cursor.ico", "image/x-icon".parse().unwrap()); + test_sniff_classification_sup("test_cursor.ico", "image", "x-icon"); } #[test] fn test_sniff_bmp() { - test_sniff_classification_sup("test.bmp", mime::IMAGE_BMP); + test_sniff_classification_sup("test.bmp", "image", "bmp"); } #[test] fn test_sniff_gif87a() { - test_sniff_classification_sup("test87a", mime::IMAGE_GIF); + test_sniff_classification_sup("test87a", "image", "gif"); } #[test] fn test_sniff_gif89a() { - test_sniff_classification_sup("test89a.gif", mime::IMAGE_GIF); + test_sniff_classification_sup("test89a.gif", "image", "gif"); } #[test] fn test_sniff_webp() { - test_sniff_classification_sup("test.webp", "image/webp".parse().unwrap()); + test_sniff_classification_sup("test.webp", "image", "webp"); } #[test] fn test_sniff_png() { - test_sniff_classification_sup("test.png", mime::IMAGE_PNG); + test_sniff_classification_sup("test.png", "image", "png"); } #[test] fn test_sniff_jpg() { - test_sniff_classification_sup("test.jpg", mime::IMAGE_JPEG); + test_sniff_classification_sup("test.jpg", "image", "jpeg"); } #[test] fn test_sniff_webm() { - test_sniff_classification_sup("test.webm", "video/webm".parse().unwrap()); + test_sniff_classification_sup("test.webm", "video", "webm"); } #[test] fn test_sniff_mp4() { - test_sniff_classification_sup("test.mp4", "video/mp4".parse().unwrap()); + test_sniff_classification_sup("test.mp4", "video", "mp4"); } #[test] fn test_sniff_avi() { - test_sniff_classification_sup("test.avi", "video/avi".parse().unwrap()); + test_sniff_classification_sup("test.avi", "video", "avi"); } #[test] fn test_sniff_basic() { - test_sniff_classification_sup("test.au", "audio/basic".parse().unwrap()); + test_sniff_classification_sup("test.au", "audio", "basic"); } #[test] fn test_sniff_aiff() { - test_sniff_classification_sup("test.aif", "audio/aiff".parse().unwrap()); + test_sniff_classification_sup("test.aif", "audio", "aiff"); } #[test] fn test_sniff_mpeg() { - test_sniff_classification_sup("test.mp3", "audio/mpeg".parse().unwrap()); + test_sniff_classification_sup("test.mp3", "audio", "mpeg"); } #[test] fn test_sniff_midi() { - test_sniff_classification_sup("test.mid", "audio/midi".parse().unwrap()); + test_sniff_classification_sup("test.mid", "audio", "midi"); } #[test] fn test_sniff_wave() { - test_sniff_classification_sup("test.wav", "audio/wave".parse().unwrap()); + test_sniff_classification_sup("test.wav", "audio", "wave"); } #[test] fn test_sniff_ogg() { - test_sniff_classification("small.ogg", "application/ogg".parse().unwrap(), None); - test_sniff_classification( - "small.ogg", - "application/ogg".parse().unwrap(), - Some("audio/".parse().unwrap()), - ); + test_sniff_classification("small.ogg", "application", "ogg", None); + test_sniff_classification("small.ogg", "application", "ogg", Some(("audio", ""))); } #[test] #[should_panic] fn test_sniff_vsn_ms_fontobject() { - test_sniff_classification_sup( - "vnd.ms-fontobject", - "application/vnd.ms-fontobject".parse().unwrap(), - ); + test_sniff_classification_sup("vnd.ms-fontobject", "application", "vnd.ms-fontobject"); } #[test] #[should_panic] fn test_sniff_true_type() { - test_sniff_full( - &PathBuf::from("unknown/true_type.ttf"), - "(TrueType)/".parse().unwrap(), - None, - ); + test_sniff_full(&PathBuf::from("unknown/true_type.ttf"), "(TrueType)", "", None); } #[test] #[should_panic] fn test_sniff_open_type() { - test_sniff_full( - &PathBuf::from("unknown/open_type"), - "(OpenType)/".parse().unwrap(), - None, - ); + test_sniff_full(&PathBuf::from("unknown/open_type"), "(OpenType)", "", None); } #[test] #[should_panic] fn test_sniff_true_type_collection() { - test_sniff_full( - &PathBuf::from("unknown/true_type_collection.ttc"), - "(TrueType Collection)/".parse().unwrap(), - None, - ); + test_sniff_full(&PathBuf::from("unknown/true_type_collection.ttc"), "(TrueType Collection)", "", None); } #[test] #[should_panic] fn test_sniff_woff() { - test_sniff_classification_sup("test.wof", "application/font-woff".parse().unwrap()); + test_sniff_classification_sup("test.wof", "application", "font-woff"); } #[test] fn test_sniff_gzip() { - test_sniff_classification("test.gz", "application/x-gzip".parse().unwrap(), None); + test_sniff_classification("test.gz", "application", "x-gzip", None); } #[test] fn test_sniff_zip() { - test_sniff_classification("test.zip", "application/zip".parse().unwrap(), None); + test_sniff_classification("test.zip", "application", "zip", None); } #[test] fn test_sniff_rar() { - test_sniff_classification( - "test.rar", - "application/x-rar-compressed".parse().unwrap(), - None, - ); + test_sniff_classification("test.rar", "application", "x-rar-compressed", None); } #[test] fn test_sniff_text_html_doctype_20() { - test_sniff_classification("text_html_doctype_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_doctype_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_doctype_20.html", "text", "html", None); + test_sniff_classification("text_html_doctype_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_doctype_3e() { - test_sniff_classification("text_html_doctype_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_doctype_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_doctype_3e.html", "text", "html", None); + test_sniff_classification("text_html_doctype_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_page_20() { - test_sniff_classification("text_html_page_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_page_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_page_20.html", "text", "html", None); + test_sniff_classification("text_html_page_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_page_3e() { - test_sniff_classification("text_html_page_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_page_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_page_3e.html", "text", "html", None); + test_sniff_classification("text_html_page_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_head_20() { - test_sniff_classification("text_html_head_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_head_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_head_20.html", "text", "html", None); + test_sniff_classification("text_html_head_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_head_3e() { - test_sniff_classification("text_html_head_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_head_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_head_3e.html", "text", "html", None); + test_sniff_classification("text_html_head_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_script_20() { - test_sniff_classification("text_html_script_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_script_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_script_20.html", "text", "html", None); + test_sniff_classification("text_html_script_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_script_3e() { - test_sniff_classification("text_html_script_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_script_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_script_3e.html", "text", "html", None); + test_sniff_classification("text_html_script_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_iframe_20() { - test_sniff_classification("text_html_iframe_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_iframe_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_iframe_20.html", "text", "html", None); + test_sniff_classification("text_html_iframe_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_iframe_3e() { - test_sniff_classification("text_html_iframe_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_iframe_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_iframe_3e.html", "text", "html", None); + test_sniff_classification("text_html_iframe_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_h1_20() { - test_sniff_classification("text_html_h1_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_h1_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_h1_20.html", "text", "html", None); + test_sniff_classification("text_html_h1_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_h1_3e() { - test_sniff_classification("text_html_h1_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_h1_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_h1_3e.html", "text", "html", None); + test_sniff_classification("text_html_h1_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_div_20() { - test_sniff_classification("text_html_div_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_div_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_div_20.html", "text", "html", None); + test_sniff_classification("text_html_div_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_div_3e() { - test_sniff_classification("text_html_div_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_div_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_div_3e.html", "text", "html", None); + test_sniff_classification("text_html_div_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_font_20() { - test_sniff_classification("text_html_font_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_font_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_font_20.html", "text", "html", None); + test_sniff_classification("text_html_font_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_font_3e() { - test_sniff_classification("text_html_font_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_font_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_font_3e.html", "text", "html", None); + test_sniff_classification("text_html_font_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_table_20() { - test_sniff_classification("text_html_table_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_table_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_table_20.html", "text", "html", None); + test_sniff_classification("text_html_table_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_table_3e() { - test_sniff_classification("text_html_table_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_table_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_table_3e.html", "text", "html", None); + test_sniff_classification("text_html_table_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_a_20() { - test_sniff_classification("text_html_a_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_a_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_a_20.html", "text", "html", None); + test_sniff_classification("text_html_a_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_a_3e() { - test_sniff_classification("text_html_a_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_a_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_a_3e.html", "text", "html", None); + test_sniff_classification("text_html_a_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_style_20() { - test_sniff_classification("text_html_style_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_style_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_style_20.html", "text", "html", None); + test_sniff_classification("text_html_style_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_style_3e() { - test_sniff_classification("text_html_style_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_style_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_style_3e.html", "text", "html", None); + test_sniff_classification("text_html_style_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_title_20() { - test_sniff_classification("text_html_title_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_title_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_title_20.html", "text", "html", None); + test_sniff_classification("text_html_title_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_title_3e() { - test_sniff_classification("text_html_title_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_title_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_title_3e.html", "text", "html", None); + test_sniff_classification("text_html_title_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_b_20() { - test_sniff_classification("text_html_b_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_b_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_b_20.html", "text", "html", None); + test_sniff_classification("text_html_b_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_b_3e() { - test_sniff_classification("text_html_b_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_b_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_b_3e.html", "text", "html", None); + test_sniff_classification("text_html_b_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_body_20() { - test_sniff_classification("text_html_body_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_body_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_body_20.html", "text", "html", None); + test_sniff_classification("text_html_body_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_body_3e() { - test_sniff_classification("text_html_body_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_body_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_body_3e.html", "text", "html", None); + test_sniff_classification("text_html_body_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_br_20() { - test_sniff_classification("text_html_br_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_br_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_br_20.html", "text", "html", None); + test_sniff_classification("text_html_br_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_br_3e() { - test_sniff_classification("text_html_br_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_br_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_br_3e.html", "text", "html", None); + test_sniff_classification("text_html_br_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_p_20() { - test_sniff_classification("text_html_p_20.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_p_20_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_p_20.html", "text", "html", None); + test_sniff_classification("text_html_p_20_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_p_3e() { - test_sniff_classification("text_html_p_3e.html", mime::TEXT_HTML, None); - test_sniff_classification("text_html_p_3e_u.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_p_3e.html", "text", "html", None); + test_sniff_classification("text_html_p_3e_u.html", "text", "html", None); } #[test] fn test_sniff_text_html_comment_20() { - test_sniff_classification("text_html_comment_20.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_comment_20.html", "text", "html", None); } #[test] fn test_sniff_text_html_comment_3e() { - test_sniff_classification("text_html_comment_3e.html", mime::TEXT_HTML, None); + test_sniff_classification("text_html_comment_3e.html", "text", "html", None); } #[test] fn test_sniff_xml() { - test_sniff_classification("test.xml", mime::TEXT_XML, None); + test_sniff_classification("test.xml", "text", "xml", None); } #[test] fn test_sniff_pdf() { - test_sniff_classification("test.pdf", mime::APPLICATION_PDF, None); + test_sniff_classification("test.pdf", "application", "pdf", None); } #[test] fn test_sniff_postscript() { - test_sniff_classification("test.ps", "application/postscript".parse().unwrap(), None); + test_sniff_classification("test.ps", "application", "postscript", None); } #[test] fn test_sniff_utf_16be_bom() { - test_sniff_classification("utf16bebom.txt", mime::TEXT_PLAIN, None); + test_sniff_classification("utf16bebom.txt", "text", "plain", None); } #[test] fn test_sniff_utf_16le_bom() { - test_sniff_classification("utf16lebom.txt", mime::TEXT_PLAIN, None); + test_sniff_classification("utf16lebom.txt", "text", "plain", None); } #[test] fn test_sniff_utf_8_bom() { - test_sniff_classification("utf8bom.txt", mime::TEXT_PLAIN, None); + test_sniff_classification("utf8bom.txt", "text", "plain", None); } #[test] fn test_sniff_rss_feed() { // RSS feeds - test_sniff_full( - &PathBuf::from("text/xml/feed.rss"), - "application/rss+xml".parse().unwrap(), - Some(mime::TEXT_HTML), - ); - test_sniff_full( - &PathBuf::from("text/xml/rdf_rss.xml"), - "application/rss+xml".parse().unwrap(), - Some(mime::TEXT_HTML), - ); + test_sniff_full(&PathBuf::from("text/xml/feed.rss"), "application", "rss+xml", Some(("text", "html"))); + test_sniff_full(&PathBuf::from("text/xml/rdf_rss.xml"), "application", "rss+xml", Some(("text", "html"))); // Not RSS feeds - test_sniff_full( - &PathBuf::from("text/xml/rdf_rss_ko_1.xml"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - ); - test_sniff_full( - &PathBuf::from("text/xml/rdf_rss_ko_2.xml"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - ); - test_sniff_full( - &PathBuf::from("text/xml/rdf_rss_ko_3.xml"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - ); - test_sniff_full( - &PathBuf::from("text/xml/rdf_rss_ko_4.xml"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - ); + test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_1.xml"), "text", "html", Some(("text", "html"))); + test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_2.xml"), "text", "html", Some(("text", "html"))); + test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_3.xml"), "text", "html", Some(("text", "html"))); + test_sniff_full(&PathBuf::from("text/xml/rdf_rss_ko_4.xml"), "text", "html", Some(("text", "html"))); } #[test] fn test_sniff_atom_feed() { - test_sniff_full( - &PathBuf::from("text/xml/feed.atom"), - "application/atom+xml".parse().unwrap(), - Some(mime::TEXT_HTML), - ); + test_sniff_full(&PathBuf::from("text/xml/feed.atom"), "application", "atom+xml", Some(("text", "html"))); } #[test] fn test_sniff_binary_file() { - test_sniff_full( - &PathBuf::from("unknown/binary_file"), - mime::APPLICATION_OCTET_STREAM, - None, - ); + test_sniff_full(&PathBuf::from("unknown/binary_file"), "application", "octet-stream", None); } #[test] fn test_sniff_atom_feed_with_no_sniff_flag_on() { - test_sniff_with_flags( - &PathBuf::from("text/xml/feed.atom"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - NoSniffFlag::On, - ApacheBugFlag::Off, - ); + test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"), + "text", + "html", + Some(("text", "html")), + NoSniffFlag::On, + ApacheBugFlag::Off); } #[test] fn test_sniff_with_no_sniff_flag_on_and_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("text/xml/feed.atom"), - mime::TEXT_HTML, - Some(mime::TEXT_HTML), - NoSniffFlag::On, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("text/xml/feed.atom"), + "text", + "html", + Some(("text", "html")), + NoSniffFlag::On, + ApacheBugFlag::On); } #[test] fn test_sniff_utf_8_bom_with_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("text/plain/utf8bom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("text/plain/utf8bom.txt"), + "text", + "plain", + Some(("dummy", "text")), + NoSniffFlag::Off, + ApacheBugFlag::On); } #[test] fn test_sniff_utf_16be_bom_with_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("text/plain/utf16bebom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("text/plain/utf16bebom.txt"), + "text", + "plain", + Some(("dummy", "text")), + NoSniffFlag::Off, + ApacheBugFlag::On); } #[test] fn test_sniff_utf_16le_bom_with_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("text/plain/utf16lebom.txt"), - mime::TEXT_PLAIN, - Some("dummy/text".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("text/plain/utf16lebom.txt"), + "text", + "plain", + Some(("dummy", "text")), + NoSniffFlag::Off, + ApacheBugFlag::On); } #[test] fn test_sniff_octet_stream_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("unknown/binary_file"), - mime::APPLICATION_OCTET_STREAM, - Some("dummy/binary".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("unknown/binary_file"), + "application", + "octet-stream", + Some(("dummy", "binary")), + NoSniffFlag::Off, + ApacheBugFlag::On); } #[test] fn test_sniff_mp4_video_apache_flag_on() { - test_sniff_with_flags( - &PathBuf::from("video/mp4/test.mp4"), - mime::APPLICATION_OCTET_STREAM, - Some("video/mp4".parse().unwrap()), - NoSniffFlag::Off, - ApacheBugFlag::On, - ); + test_sniff_with_flags(&PathBuf::from("video/mp4/test.mp4"), + "application", + "octet-stream", + Some(("video", "mp4")), + NoSniffFlag::Off, + ApacheBugFlag::On); } diff --git a/components/net/tests/resource_thread.rs b/components/net/tests/resource_thread.rs index b33e28942fa4..575b67dc7de6 100644 --- a/components/net/tests/resource_thread.rs +++ b/components/net/tests/resource_thread.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::create_embedder_proxy; +use create_embedder_proxy; use ipc_channel::ipc; use net::resource_thread::new_core_resource_thread; use net::test::parse_hostsfile; @@ -21,13 +21,7 @@ fn test_exit() { let (mtx, _mrx) = ipc::channel().unwrap(); let (sender, receiver) = ipc::channel().unwrap(); let (resource_thread, _private_resource_thread) = new_core_resource_thread( - "".into(), - None, - ProfilerChan(tx), - MemProfilerChan(mtx), - create_embedder_proxy(), - None, - ); + "".into(), None, ProfilerChan(tx), MemProfilerChan(mtx), create_embedder_proxy(), None); resource_thread.send(CoreResourceMsg::Exit(sender)).unwrap(); receiver.recv().unwrap(); } @@ -38,16 +32,12 @@ fn test_parse_hostsfile() { let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!( - ip("127.0.0.2"), - *hosts_table.get("servo.test.server").unwrap() - ); + assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); } #[test] fn test_parse_malformed_hostsfile() { - let mock_hosts_file_content = - "malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1"; + let mock_hosts_file_content = "malformed file\n127.0.0.1 foo.bar.com\nservo.test.server 127.0.0.1"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(1, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); @@ -55,8 +45,7 @@ fn test_parse_malformed_hostsfile() { #[test] fn test_parse_hostsfile_with_line_comment() { - let mock_hosts_file_content = - "# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment"; + let mock_hosts_file_content = "# this is a line comment\n127.0.0.1 foo.bar.com\n# anothercomment"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(1, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); @@ -64,15 +53,11 @@ fn test_parse_hostsfile_with_line_comment() { #[test] fn test_parse_hostsfile_with_end_of_line_comment() { - let mock_hosts_file_content = - "127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment"; + let mock_hosts_file_content = "127.0.0.1 foo.bar.com # line ending comment\n127.0.0.2 servo.test.server #comment"; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!( - ip("127.0.0.2"), - *hosts_table.get("servo.test.server").unwrap() - ); + assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); } #[test] @@ -101,14 +86,12 @@ fn test_parse_hostsfile_with_tabs_instead_spaces() { let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(2, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!( - ip("127.0.0.2"), - *hosts_table.get("servo.test.server").unwrap() - ); + assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); } #[test] -fn test_parse_hostsfile_with_valid_ipv4_addresses() { +fn test_parse_hostsfile_with_valid_ipv4_addresses() +{ let mock_hosts_file_content = "255.255.255.255 foo.bar.com\n169.0.1.201 servo.test.server\n192.168.5.0 servo.foo.com"; let hosts_table = parse_hostsfile(mock_hosts_file_content); @@ -116,7 +99,8 @@ fn test_parse_hostsfile_with_valid_ipv4_addresses() { } #[test] -fn test_parse_hostsfile_with_invalid_ipv4_addresses() { +fn test_parse_hostsfile_with_invalid_ipv4_addresses() +{ let mock_hosts_file_content = "256.255.255.255 foo.bar.com\n169.0.1000.201 servo.test.server \ \n192.168.5.500 servo.foo.com\n192.abc.100.2 test.servo.com"; let hosts_table = parse_hostsfile(mock_hosts_file_content); @@ -124,7 +108,8 @@ fn test_parse_hostsfile_with_invalid_ipv4_addresses() { } #[test] -fn test_parse_hostsfile_with_valid_ipv6_addresses() { +fn test_parse_hostsfile_with_valid_ipv6_addresses() +{ let mock_hosts_file_content = "2001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\ 2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n\ 2001:db8::ff00:42:8329 foo.moz.com moz.moz.com\n\ @@ -137,7 +122,8 @@ fn test_parse_hostsfile_with_valid_ipv6_addresses() { } #[test] -fn test_parse_hostsfile_with_invalid_ipv6_addresses() { +fn test_parse_hostsfile_with_invalid_ipv6_addresses() +{ let mock_hosts_file_content = "12001:0db8:0000:0000:0000:ff00:0042:8329 foo.bar.com\n\ 2001:zdb8:0:0:0:gg00:42:t329 moz.foo.com\n\ 2002:0DB8:85A3:0042:1000:8A2E:0370:7334/1289 baz3.bar.moz"; @@ -146,19 +132,14 @@ fn test_parse_hostsfile_with_invalid_ipv6_addresses() { } #[test] -fn test_parse_hostsfile_with_end_of_line_whitespace() { +fn test_parse_hostsfile_with_end_of_line_whitespace() +{ let mock_hosts_file_content = "127.0.0.1 foo.bar.com \n\ 2001:db8:0:0:0:ff00:42:8329 moz.foo.com\n \ 127.0.0.2 servo.test.server "; let hosts_table = parse_hostsfile(mock_hosts_file_content); assert_eq!(3, hosts_table.len()); assert_eq!(ip("127.0.0.1"), *hosts_table.get("foo.bar.com").unwrap()); - assert_eq!( - ip("2001:db8:0:0:0:ff00:42:8329"), - *hosts_table.get("moz.foo.com").unwrap() - ); - assert_eq!( - ip("127.0.0.2"), - *hosts_table.get("servo.test.server").unwrap() - ); + assert_eq!(ip("2001:db8:0:0:0:ff00:42:8329"), *hosts_table.get("moz.foo.com").unwrap()); + assert_eq!(ip("127.0.0.2"), *hosts_table.get("servo.test.server").unwrap()); } diff --git a/components/net/tests/subresource_integrity.rs b/components/net/tests/subresource_integrity.rs index 3cd5ac2b017c..d67da9c17753 100644 --- a/components/net/tests/subresource_integrity.rs +++ b/components/net/tests/subresource_integrity.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use net::subresource_integrity::{get_prioritized_hash_function, get_strongest_metadata, SriEntry}; +use net::subresource_integrity::{SriEntry, get_prioritized_hash_function, get_strongest_metadata}; use net::subresource_integrity::{is_response_integrity_valid, parsed_metadata}; use net_traits::response::{Response, ResponseBody}; use servo_url::ServoUrl; @@ -72,8 +72,7 @@ fn test_response_integrity_valid() { let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap(); let response: Response = Response::new(url); - let integrity_metadata = - "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; + let integrity_metadata = "sha384-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; let response_body = "alert('Hello, world.');".to_owned().into_bytes(); *response.body.lock().unwrap() = ResponseBody::Done(response_body); @@ -85,8 +84,7 @@ fn test_response_integrity_invalid() { let url: ServoUrl = ServoUrl::parse("http://servo.org").unwrap(); let response: Response = Response::new(url); - let integrity_metadata = - "sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; + let integrity_metadata = "sha256-H8BRh8j48O9oYatfu5AZzq6A9RINhZO5H16dQZngK7T62em8MUt1FLm52t+eX6xO"; let response_body = "alert('Hello, world.');".to_owned().into_bytes(); *response.body.lock().unwrap() = ResponseBody::Done(response_body); diff --git a/components/net/websocket_loader.rs b/components/net/websocket_loader.rs index 85149c60ec07..5a676c904ad0 100644 --- a/components/net/websocket_loader.rs +++ b/components/net/websocket_loader.rs @@ -2,33 +2,28 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::connector::create_ssl_connector_builder; -use crate::cookie::Cookie; -use crate::fetch::methods::should_be_blocked_due_to_bad_port; -use crate::hosts::replace_host; -use crate::http_loader::HttpState; +use connector::create_ssl_connector; +use cookie::Cookie; use embedder_traits::resources::{self, Resource}; -use headers_ext::Host; -use http::header::{self, HeaderMap, HeaderName, HeaderValue}; -use http::uri::Authority; +use fetch::methods::should_be_blocked_due_to_bad_port; +use hosts::replace_host; +use http_loader::HttpState; +use hyper::header::{Headers, Host, SetCookie}; use ipc_channel::ipc::{IpcReceiver, IpcSender}; -use net_traits::request::{RequestInit, RequestMode}; use net_traits::{CookieSource, MessageData}; use net_traits::{WebSocketDomAction, WebSocketNetworkEvent}; +use net_traits::request::{RequestInit, RequestMode}; use openssl::ssl::SslStream; use servo_config::opts; use servo_url::ServoUrl; use std::fs; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; use std::thread; use url::Url; -use ws::util::TcpStream; -use ws::{ - CloseCode, Factory, Handler, Handshake, Message, Request, Response as WsResponse, Sender, - WebSocket, -}; +use ws::{CloseCode, Factory, Handler, Handshake, Message, Request, Response as WsResponse, Sender, WebSocket}; use ws::{Error as WebSocketError, ErrorKind as WebSocketErrorKind, Result as WebSocketResult}; +use ws::util::TcpStream; /// A client for connecting to a websocket server #[derive(Clone)] @@ -54,85 +49,71 @@ impl<'a> Factory for Client<'a> { } } + impl<'a> Handler for Client<'a> { fn build_request(&mut self, url: &Url) -> WebSocketResult { let mut req = Request::from_url(url)?; - req.headers_mut() - .push(("Origin".to_string(), self.origin.as_bytes().to_owned())); - req.headers_mut().push(( - "Host".to_string(), - format!("{}", self.host).as_bytes().to_owned(), - )); + req.headers_mut().push(("Origin".to_string(), self.origin.as_bytes().to_owned())); + req.headers_mut().push(("Host".to_string(), format!("{}", self.host).as_bytes().to_owned())); for protocol in self.protocols { req.add_protocol(protocol); - } + }; let mut cookie_jar = self.http_state.cookie_jar.write().unwrap(); - if let Some(cookie_list) = cookie_jar.cookies_for_url(self.resource_url, CookieSource::HTTP) - { - req.headers_mut() - .push(("Cookie".into(), cookie_list.as_bytes().to_owned())) + if let Some(cookie_list) = cookie_jar.cookies_for_url(self.resource_url, CookieSource::HTTP) { + req.headers_mut().push(("Cookie".into(), cookie_list.as_bytes().to_owned())) } Ok(req) } fn on_open(&mut self, shake: Handshake) -> WebSocketResult<()> { - let mut headers = HeaderMap::new(); + let mut headers = Headers::new(); for &(ref name, ref value) in shake.response.headers().iter() { - let name = HeaderName::from_bytes(name.as_bytes()).unwrap(); - let value = HeaderValue::from_bytes(&value).unwrap(); - - headers.insert(name, value); + headers.set_raw(name.clone(), vec![value.clone()]); } - let mut jar = self.http_state.cookie_jar.write().unwrap(); - // TODO(eijebong): Replace thise once typed headers settled on a cookie impl - for cookie in headers.get_all(header::SET_COOKIE) { - if let Ok(s) = cookie.to_str() { + if let Some(cookies) = headers.get::() { + let mut jar = self.http_state.cookie_jar.write().unwrap(); + for cookie in &**cookies { if let Some(cookie) = - Cookie::from_cookie_string(s.into(), self.resource_url, CookieSource::HTTP) + Cookie::from_cookie_string(cookie.clone(), self.resource_url, CookieSource::HTTP) { jar.push(cookie, self.resource_url, CookieSource::HTTP); } } } - let _ = self - .event_sender - .send(WebSocketNetworkEvent::ConnectionEstablished { - protocol_in_use: self.protocol_in_use.clone(), - }); + let _ = self.event_sender.send( + WebSocketNetworkEvent::ConnectionEstablished { protocol_in_use: self.protocol_in_use.clone() }); Ok(()) } - fn on_message(&mut self, message: Message) -> WebSocketResult<()> { + fn on_message(&mut self, message: Message) -> WebSocketResult<()> { let message = match message { Message::Text(message) => MessageData::Text(message), Message::Binary(message) => MessageData::Binary(message), }; - let _ = self - .event_sender - .send(WebSocketNetworkEvent::MessageReceived(message)); + let _ = self.event_sender.send(WebSocketNetworkEvent::MessageReceived(message)); Ok(()) } + fn on_error(&mut self, err: WebSocketError) { debug!("Error in WebSocket communication: {:?}", err); let _ = self.event_sender.send(WebSocketNetworkEvent::Fail); } + fn on_response(&mut self, res: &WsResponse) -> WebSocketResult<()> { let protocol_in_use = res.protocol()?; if let Some(protocol_name) = protocol_in_use { if !self.protocols.is_empty() && !self.protocols.iter().any(|p| protocol_name == (*p)) { - let error = WebSocketError::new( - WebSocketErrorKind::Protocol, - "Protocol in Use not in client-supplied protocol list", - ); + let error = WebSocketError::new(WebSocketErrorKind::Protocol, + "Protocol in Use not in client-supplied protocol list"); return Err(error); } self.protocol_in_use = Some(protocol_name.into()); @@ -142,10 +123,7 @@ impl<'a> Handler for Client<'a> { fn on_close(&mut self, code: CloseCode, reason: &str) { debug!("Connection closing due to ({:?}) {}", code, reason); - let _ = self.event_sender.send(WebSocketNetworkEvent::Close( - Some(code.into()), - reason.to_owned(), - )); + let _ = self.event_sender.send(WebSocketNetworkEvent::Close(Some(code.into()), reason.to_owned())); } fn upgrade_ssl_client( @@ -154,120 +132,105 @@ impl<'a> Handler for Client<'a> { url: &Url, ) -> WebSocketResult> { let certs = match opts::get().certificate_path { - Some(ref path) => fs::read_to_string(path).expect("Couldn't not find certificate file"), - None => resources::read_string(Resource::SSLCertificates), + Some(ref path) => { + fs::read_to_string(path).expect("Couldn't not find certificate file") + } + None => { + resources::read_string(Resource::SSLCertificates) + }, }; - let domain = self - .resource_url - .as_url() - .domain() - .ok_or(WebSocketError::new( - WebSocketErrorKind::Protocol, - format!("Unable to parse domain from {}. Needed for SSL.", url), - ))?; - let connector = create_ssl_connector_builder(&certs).build(); - connector - .connect(domain, stream) - .map_err(WebSocketError::from) + let domain = self.resource_url.as_url().domain().ok_or(WebSocketError::new( + WebSocketErrorKind::Protocol, + format!("Unable to parse domain from {}. Needed for SSL.", url), + ))?; + let connector = create_ssl_connector(&certs); + connector.connect(domain, stream).map_err(WebSocketError::from) } + } pub fn init( req_init: RequestInit, resource_event_sender: IpcSender, dom_action_receiver: IpcReceiver, - http_state: Arc, + http_state: Arc ) { - thread::Builder::new() - .name(format!("WebSocket connection to {}", req_init.url)) - .spawn(move || { - let protocols = match req_init.mode { - RequestMode::WebSocket { protocols } => protocols.clone(), - _ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"), - }; - - let scheme = req_init.url.scheme(); - let mut req_url = req_init.url.clone(); - if scheme == "ws" { - req_url.as_mut_url().set_scheme("http").unwrap(); - } else if scheme == "wss" { - req_url.as_mut_url().set_scheme("https").unwrap(); - } + thread::Builder::new().name(format!("WebSocket connection to {}", req_init.url)).spawn(move || { + let protocols = match req_init.mode { + RequestMode::WebSocket { protocols } => protocols.clone(), + _ => panic!("Received a RequestInit with a non-websocket mode in websocket_loader"), + }; - if should_be_blocked_due_to_bad_port(&req_url) { - debug!("Failed to establish a WebSocket connection: port blocked"); - let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); - return; - } + let scheme = req_init.url.scheme(); + let mut req_url = req_init.url.clone(); + if scheme == "ws" { + req_url.as_mut_url().set_scheme("http").unwrap(); + } else if scheme == "wss" { + req_url.as_mut_url().set_scheme("https").unwrap(); + } + + if should_be_blocked_due_to_bad_port(&req_url) { + debug!("Failed to establish a WebSocket connection: port blocked"); + let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); + return; + } - let host = replace_host(req_init.url.host_str().unwrap()); - let mut net_url = req_init.url.clone().into_url(); - net_url.set_host(Some(&host)).unwrap(); - - let host = Host::from( - format!( - "{}{}", - req_init.url.host_str().unwrap(), - req_init - .url - .port_or_known_default() - .map(|v| format!(":{}", v)) - .unwrap_or("".into()) - ) - .parse::() - .unwrap(), - ); - - let client = Client { - origin: &req_init.origin.ascii_serialization(), - host: &host, - protocols: &protocols, - http_state: &http_state, - resource_url: &req_init.url, - event_sender: &resource_event_sender, - protocol_in_use: None, - }; - let mut ws = WebSocket::new(client).unwrap(); - - if let Err(e) = ws.connect(net_url) { - debug!("Failed to establish a WebSocket connection: {:?}", e); - return; - }; - - let ws_sender = ws.broadcaster(); - let initiated_close = Arc::new(AtomicBool::new(false)); - - thread::spawn(move || { - while let Ok(dom_action) = dom_action_receiver.recv() { - match dom_action { - WebSocketDomAction::SendMessage(MessageData::Text(data)) => { - ws_sender.send(Message::text(data)).unwrap(); - }, - WebSocketDomAction::SendMessage(MessageData::Binary(data)) => { - ws_sender.send(Message::binary(data)).unwrap(); - }, - WebSocketDomAction::Close(code, reason) => { - if !initiated_close.fetch_or(true, Ordering::SeqCst) { - match code { - Some(code) => ws_sender - .close_with_reason( - code.into(), - reason.unwrap_or("".to_owned()), - ) - .unwrap(), - None => ws_sender.close(CloseCode::Status).unwrap(), - }; - } - }, - } + let host = replace_host(req_init.url.host_str().unwrap()); + let mut net_url = req_init.url.clone().into_url(); + net_url.set_host(Some(&host)).unwrap(); + + let host = Host { + hostname: req_init.url.host_str().unwrap().to_owned(), + port: req_init.url.port_or_known_default(), + }; + + let client = Client { + origin: &req_init.origin.ascii_serialization(), + host: &host, + protocols: &protocols, + http_state: &http_state, + resource_url: &req_init.url, + event_sender: &resource_event_sender, + protocol_in_use: None, + }; + let mut ws = WebSocket::new(client).unwrap(); + + if let Err(e) = ws.connect(net_url) { + debug!("Failed to establish a WebSocket connection: {:?}", e); + return; + }; + + let ws_sender = ws.broadcaster(); + let initiated_close = Arc::new(AtomicBool::new(false)); + + thread::spawn(move || { + while let Ok(dom_action) = dom_action_receiver.recv() { + match dom_action { + WebSocketDomAction::SendMessage(MessageData::Text(data)) => { + ws_sender.send(Message::text(data)).unwrap(); + }, + WebSocketDomAction::SendMessage(MessageData::Binary(data)) => { + ws_sender.send(Message::binary(data)).unwrap(); + }, + WebSocketDomAction::Close(code, reason) => { + if !initiated_close.fetch_or(true, Ordering::SeqCst) { + match code { + Some(code) => { + ws_sender.close_with_reason(code.into(), reason.unwrap_or("".to_owned())).unwrap() + }, + None => ws_sender.close(CloseCode::Status).unwrap(), + }; + } + }, } - }); - - if let Err(e) = ws.run() { - debug!("Failed to run WebSocket: {:?}", e); - let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); - }; - }) - .expect("Thread spawning failed"); + } + }); + + if let Err(e) = ws.run() { + debug!("Failed to run WebSocket: {:?}", e); + let _ = resource_event_sender.send(WebSocketNetworkEvent::Fail); + }; + }).expect("Thread spawning failed"); } + diff --git a/components/net_traits/Cargo.toml b/components/net_traits/Cargo.toml index 6fb2c926dd86..9ae5042be69d 100644 --- a/components/net_traits/Cargo.toml +++ b/components/net_traits/Cargo.toml @@ -1,11 +1,8 @@ -cargo-features = ["rename-dependency"] - [package] name = "net_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -15,23 +12,18 @@ test = false doctest = false [dependencies] -cookie = "0.11" +cookie = "0.10" embedder_traits = { path = "../embedder_traits" } -headers-core = "0.0.1" -headers-ext = "0.0.3" -http = "0.1" -hyper = "0.12" -hyper_serde = "0.9" -piston_image = {package = "image", version = "0.19"} +hyper = "0.10" +hyper_serde = "0.8" +image = "0.19" ipc-channel = "0.11" lazy_static = "1" log = "0.4" malloc_size_of = { path = "../malloc_size_of" } malloc_size_of_derive = { path = "../malloc_size_of_derive" } -mime = "0.3" msg = {path = "../msg"} num-traits = "0.2" -pixels = {path = "../pixels"} serde = "1.0" servo_arc = {path = "../servo_arc"} servo_config = {path = "../config"} @@ -41,4 +33,4 @@ uuid = {version = "0.6", features = ["v4", "serde"]} webrender_api = {git = "https://github.com/servo/webrender", features = ["ipc"]} [dev-dependencies] -std_test_override = { path = "../std_test_override" } +embedder_traits = { path = "../embedder_traits", features = ["tests"] } diff --git a/components/net_traits/blob_url_store.rs b/components/net_traits/blob_url_store.rs index 961d7ae20ad4..b35134bd78c2 100644 --- a/components/net_traits/blob_url_store.rs +++ b/components/net_traits/blob_url_store.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::filemanager_thread::FileOrigin; +use filemanager_thread::FileOrigin; use servo_url::ServoUrl; use std::str::FromStr; use url::Url; @@ -57,6 +57,6 @@ pub fn get_blob_origin(url: &ServoUrl) -> FileOrigin { // NOTE: by default this is "null" (Opaque), which is not ideal "file://".to_string() } else { - url.origin().ascii_serialization() + url.origin().unicode_serialization() } } diff --git a/components/net_traits/filemanager_thread.rs b/components/net_traits/filemanager_thread.rs index 5a851676d585..fa0ac23d8f5c 100644 --- a/components/net_traits/filemanager_thread.rs +++ b/components/net_traits/filemanager_thread.rs @@ -2,7 +2,7 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::blob_url_store::{BlobBuf, BlobURLStoreError}; +use blob_url_store::{BlobBuf, BlobURLStoreError}; use embedder_traits::FilterPattern; use ipc_channel::ipc::IpcSender; use num_traits::ToPrimitive; @@ -19,7 +19,7 @@ pub type FileOrigin = String; /// Relative slice positions of a sequence, /// whose semantic should be consistent with (start, end) parameters in /// -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct RelativePos { /// Relative to first byte if non-negative, /// relative to one past last byte if negative, @@ -111,49 +111,24 @@ pub struct SelectedFile { pub type_string: String, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum FileManagerThreadMsg { /// Select a single file. Last field is pre-selected file path for testing - SelectFile( - Vec, - IpcSender>, - FileOrigin, - Option, - ), + SelectFile(Vec, IpcSender>, FileOrigin, Option), /// Select multiple files. Last field is pre-selected file paths for testing - SelectFiles( - Vec, - IpcSender>>, - FileOrigin, - Option>, - ), + SelectFiles(Vec, IpcSender>>, FileOrigin, Option>), /// Read FileID-indexed file in chunks, optionally check URL validity based on boolean flag - ReadFile( - IpcSender>, - Uuid, - bool, - FileOrigin, - ), + ReadFile(IpcSender>, Uuid, bool, FileOrigin), /// Add an entry as promoted memory-based blob and send back the associated FileID /// as part of a valid/invalid Blob URL depending on the boolean flag - PromoteMemory( - BlobBuf, - bool, - IpcSender>, - FileOrigin, - ), + PromoteMemory(BlobBuf, bool, IpcSender>, FileOrigin), /// Add a sliced entry pointing to the parent FileID, and send back the associated FileID /// as part of a valid Blob URL - AddSlicedURLEntry( - Uuid, - RelativePos, - IpcSender>, - FileOrigin, - ), + AddSlicedURLEntry(Uuid, RelativePos, IpcSender>, FileOrigin), /// Decrease reference count and send back the acknowledgement DecRef(Uuid, FileOrigin, IpcSender>), diff --git a/components/net_traits/image/base.rs b/components/net_traits/image/base.rs index 6e67e5b7cd1d..40b4d5d3c473 100644 --- a/components/net_traits/image/base.rs +++ b/components/net_traits/image/base.rs @@ -3,8 +3,9 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::IpcSharedMemory; -use piston_image::{DynamicImage, ImageFormat}; +use piston_image::{self, DynamicImage, ImageFormat}; use std::fmt; +use webrender_api; #[derive(Clone, Copy, Debug, Deserialize, Eq, MallocSizeOf, PartialEq, Serialize)] pub enum PixelFormat { @@ -31,11 +32,8 @@ pub struct Image { impl fmt::Debug for Image { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}", - self.width, self.height, self.format, self.id - ) + write!(f, "Image {{ width: {}, height: {}, format: {:?}, ..., id: {:?} }}", + self.width, self.height, self.format, self.id) } } @@ -48,6 +46,24 @@ pub struct ImageMetadata { // FIXME: Images must not be copied every frame. Instead we should atomically // reference count them. +// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this. +fn byte_swap_and_premultiply(data: &mut [u8]) { + let length = data.len(); + + let mut i = 0; + while i < length { + let r = data[i + 2]; + let g = data[i + 1]; + let b = data[i + 0]; + + data[i + 0] = r; + data[i + 1] = g; + data[i + 2] = b; + + i += 4; + } +} + pub fn load_from_memory(buffer: &[u8]) -> Option { if buffer.is_empty() { return None; @@ -59,29 +75,32 @@ pub fn load_from_memory(buffer: &[u8]) -> Option { debug!("{}", msg); None }, - Ok(_) => match piston_image::load_from_memory(buffer) { - Ok(image) => { - let mut rgba = match image { - DynamicImage::ImageRgba8(rgba) => rgba, - image => image.to_rgba(), - }; - pixels::byte_swap_colors_inplace(&mut *rgba); - Some(Image { - width: rgba.width(), - height: rgba.height(), - format: PixelFormat::BGRA8, - bytes: IpcSharedMemory::from_bytes(&*rgba), - id: None, - }) - }, - Err(e) => { - debug!("Image decoding error: {:?}", e); - None - }, + Ok(_) => { + match piston_image::load_from_memory(buffer) { + Ok(image) => { + let mut rgba = match image { + DynamicImage::ImageRgba8(rgba) => rgba, + image => image.to_rgba(), + }; + byte_swap_and_premultiply(&mut *rgba); + Some(Image { + width: rgba.width(), + height: rgba.height(), + format: PixelFormat::BGRA8, + bytes: IpcSharedMemory::from_bytes(&*rgba), + id: None, + }) + }, + Err(e) => { + debug!("Image decoding error: {:?}", e); + None + }, + } }, } } + // https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img pub fn detect_image_format(buffer: &[u8]) -> Result { if is_gif(buffer) { diff --git a/components/net_traits/image_cache.rs b/components/net_traits/image_cache.rs index ab3cb4634e5c..85db07931486 100644 --- a/components/net_traits/image_cache.rs +++ b/components/net_traits/image_cache.rs @@ -2,11 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::image::base::{Image, ImageMetadata}; -use crate::FetchResponseMsg; +use FetchResponseMsg; +use image::base::{Image, ImageMetadata}; use ipc_channel::ipc::IpcSender; use servo_url::ServoUrl; use std::sync::Arc; +use webrender_api; // ====================================================================== // Aux structs and enums. @@ -15,14 +16,14 @@ use std::sync::Arc; /// Whether a consumer is in a position to request images or not. This can occur /// when animations are being processed by the layout thread while the script /// thread is executing in parallel. -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum CanRequestImages { No, Yes, } /// Indicating either entire image or just metadata availability -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub enum ImageOrMetadataAvailable { ImageAvailable(#[ignore_malloc_size_of = "Arc"] Arc, ServoUrl), MetadataAvailable(ImageMetadata), @@ -32,7 +33,7 @@ pub enum ImageOrMetadataAvailable { /// and image, and returned to the specified event loop when the /// image load completes. It is typically used to trigger a reflow /// and/or repaint. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ImageResponder { id: PendingImageId, sender: IpcSender, @@ -72,7 +73,7 @@ pub enum ImageResponse { } /// The current state of an image in the cache. -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum ImageState { Pending(PendingImageId), LoadError, @@ -89,7 +90,7 @@ pub struct PendingImageResponse { pub id: PendingImageId, } -#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, Eq, Hash, PartialEq, Serialize)] pub enum UsePlaceholder { No, Yes, @@ -100,19 +101,16 @@ pub enum UsePlaceholder { // ====================================================================== pub trait ImageCache: Sync + Send { - fn new(webrender_api: webrender_api::RenderApi) -> Self - where - Self: Sized; + fn new(webrender_api: webrender_api::RenderApi) -> Self where Self: Sized; /// Return any available metadata or image for the given URL, /// or an indication that the image is not yet available if it is in progress, /// or else reserve a slot in the cache for the URL if the consumer can request images. - fn find_image_or_metadata( - &self, - url: ServoUrl, - use_placeholder: UsePlaceholder, - can_request: CanRequestImages, - ) -> Result; + fn find_image_or_metadata(&self, + url: ServoUrl, + use_placeholder: UsePlaceholder, + can_request: CanRequestImages) + -> Result; /// Add a new listener for the given pending image id. If the image is already present, /// the responder will still receive the expected response. diff --git a/components/net_traits/lib.rs b/components/net_traits/lib.rs index b7e11fc4af5d..87dcf034caaf 100644 --- a/components/net_traits/lib.rs +++ b/components/net_traits/lib.rs @@ -2,47 +2,50 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + #![deny(unsafe_code)] -#[macro_use] -extern crate lazy_static; -#[macro_use] -extern crate log; -#[macro_use] -extern crate malloc_size_of; -#[macro_use] -extern crate malloc_size_of_derive; -#[macro_use] -extern crate serde; -#[macro_use] +extern crate cookie as cookie_rs; +extern crate embedder_traits; +extern crate hyper; +extern crate hyper_serde; +extern crate image as piston_image; +extern crate ipc_channel; +#[macro_use] extern crate lazy_static; +#[macro_use] extern crate log; +#[macro_use] extern crate malloc_size_of; +#[macro_use] extern crate malloc_size_of_derive; +extern crate msg; +extern crate num_traits; +#[macro_use] extern crate serde; +extern crate servo_arc; +extern crate servo_url; extern crate url; +extern crate uuid; +extern crate webrender_api; -use cookie::Cookie; -use crate::filemanager_thread::FileManagerThreadMsg; -use crate::request::{Request, RequestInit}; -use crate::response::{HttpsState, Response, ResponseInit}; -use crate::storage_thread::StorageThreadMsg; -use headers_core::HeaderMapExt; -use headers_ext::{ContentType, ReferrerPolicy as ReferrerPolicyHeader}; -use http::{Error as HttpError, HeaderMap}; +use cookie_rs::Cookie; +use filemanager_thread::FileManagerThreadMsg; use hyper::Error as HyperError; -use hyper::StatusCode; +use hyper::header::{ContentType, Headers, ReferrerPolicy as ReferrerPolicyHeader}; +use hyper::http::RawStatus; +use hyper::mime::{Attr, Mime}; use hyper_serde::Serde; +use ipc_channel::Error as IpcError; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; -use ipc_channel::Error as IpcError; -use mime::Mime; use msg::constellation_msg::HistoryStateId; +use request::{Request, RequestInit}; +use response::{HttpsState, Response, ResponseInit}; use servo_url::ServoUrl; use std::error::Error; -use url::percent_encoding; +use storage_thread::StorageThreadMsg; pub mod blob_url_store; pub mod filemanager_thread; pub mod image_cache; pub mod net_error_list; pub mod pub_domains; -pub mod quality; pub mod request; pub mod response; pub mod storage_thread; @@ -58,7 +61,7 @@ pub mod image { /// A loading context, for context-specific sniffing, as defined in /// -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub enum LoadContext { Browsing, Image, @@ -74,26 +77,18 @@ pub enum LoadContext { #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub struct CustomResponse { #[ignore_malloc_size_of = "Defined in hyper"] - #[serde( - deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize" - )] - pub headers: HeaderMap, + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] + pub headers: Headers, #[ignore_malloc_size_of = "Defined in hyper"] - #[serde( - deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize" - )] - pub raw_status: (StatusCode, String), + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] + pub raw_status: RawStatus, pub body: Vec, } impl CustomResponse { - pub fn new( - headers: HeaderMap, - raw_status: (StatusCode, String), - body: Vec, - ) -> CustomResponse { + pub fn new(headers: Headers, raw_status: RawStatus, body: Vec) -> CustomResponse { CustomResponse { headers: headers, raw_status: raw_status, @@ -102,7 +97,7 @@ impl CustomResponse { } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct CustomResponseMediator { pub response_chan: IpcSender>, pub load_url: ServoUrl, @@ -130,26 +125,30 @@ pub enum ReferrerPolicy { StrictOriginWhenCrossOrigin, } -impl From for ReferrerPolicy { - fn from(policy: ReferrerPolicyHeader) -> Self { - match policy { - ReferrerPolicyHeader::NO_REFERRER => ReferrerPolicy::NoReferrer, - ReferrerPolicyHeader::NO_REFERRER_WHEN_DOWNGRADE => { - ReferrerPolicy::NoReferrerWhenDowngrade - }, - ReferrerPolicyHeader::SAME_ORIGIN => ReferrerPolicy::SameOrigin, - ReferrerPolicyHeader::ORIGIN => ReferrerPolicy::Origin, - ReferrerPolicyHeader::ORIGIN_WHEN_CROSS_ORIGIN => ReferrerPolicy::OriginWhenCrossOrigin, - ReferrerPolicyHeader::UNSAFE_URL => ReferrerPolicy::UnsafeUrl, - ReferrerPolicyHeader::STRICT_ORIGIN => ReferrerPolicy::StrictOrigin, - ReferrerPolicyHeader::STRICT_ORIGIN_WHEN_CROSS_ORIGIN => { - ReferrerPolicy::StrictOriginWhenCrossOrigin - }, +impl<'a> From<&'a ReferrerPolicyHeader> for ReferrerPolicy { + fn from(policy: &'a ReferrerPolicyHeader) -> Self { + match *policy { + ReferrerPolicyHeader::NoReferrer => + ReferrerPolicy::NoReferrer, + ReferrerPolicyHeader::NoReferrerWhenDowngrade => + ReferrerPolicy::NoReferrerWhenDowngrade, + ReferrerPolicyHeader::SameOrigin => + ReferrerPolicy::SameOrigin, + ReferrerPolicyHeader::Origin => + ReferrerPolicy::Origin, + ReferrerPolicyHeader::OriginWhenCrossOrigin => + ReferrerPolicy::OriginWhenCrossOrigin, + ReferrerPolicyHeader::UnsafeUrl => + ReferrerPolicy::UnsafeUrl, + ReferrerPolicyHeader::StrictOrigin => + ReferrerPolicy::StrictOrigin, + ReferrerPolicyHeader::StrictOriginWhenCrossOrigin => + ReferrerPolicy::StrictOriginWhenCrossOrigin, } } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum FetchResponseMsg { // todo: should have fields for transmitted/total bytes ProcessRequestBody, @@ -185,15 +184,15 @@ pub trait FetchTaskTarget { fn process_response_eof(&mut self, response: &Response); } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum FilteredMetadata { Basic(Metadata), Cors(Metadata), Opaque, - OpaqueRedirect, + OpaqueRedirect } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum FetchMetadata { Unfiltered(Metadata), Filtered { @@ -236,6 +235,7 @@ impl FetchTaskTarget for IpcSender { } } + pub trait Action { fn process(self, listener: &mut Listener); } @@ -262,11 +262,10 @@ pub type IpcSendResult = Result<(), IpcError>; /// used by net_traits::ResourceThreads to ease the use its IpcSender sub-fields /// XXX: If this trait will be used more in future, some auto derive might be appealing pub trait IpcSend -where - T: serde::Serialize + for<'de> serde::Deserialize<'de>, + where T: serde::Serialize + for<'de> serde::Deserialize<'de>, { /// send message T - fn send(&self, _: T) -> IpcSendResult; + fn send(&self, T) -> IpcSendResult; /// get underlying sender fn sender(&self) -> IpcSender; } @@ -276,7 +275,7 @@ where // the "Arc" hack implicitly in future. // See discussion: http://logs.glob.uno/?c=mozilla%23servo&s=16+May+2016&e=16+May+2016#c430412 // See also: https://github.com/servo/servo/blob/735480/components/script/script_thread.rs#L313 -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ResourceThreads { core_thread: CoreResourceThread, storage_thread: IpcSender, @@ -314,55 +313,49 @@ impl IpcSend for ResourceThreads { // Ignore the sub-fields malloc_size_of_is_0!(ResourceThreads); -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum IncludeSubdomains { Included, NotIncluded, } -#[derive(Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Deserialize, MallocSizeOf, Serialize)] pub enum MessageData { Text(String), Binary(Vec), } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum WebSocketDomAction { SendMessage(MessageData), Close(Option, Option), } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum WebSocketNetworkEvent { - ConnectionEstablished { protocol_in_use: Option }, + ConnectionEstablished { + protocol_in_use: Option, + }, MessageReceived(MessageData), Close(Option, String), Fail, } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] /// IPC channels to communicate with the script thread about network or DOM events. pub enum FetchChannels { - ResponseMsg( - IpcSender, - /* cancel_chan */ Option>, - ), + ResponseMsg(IpcSender, /* cancel_chan */ Option>), WebSocket { event_sender: IpcSender, action_receiver: IpcReceiver, - }, + } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum CoreResourceMsg { Fetch(RequestInit, FetchChannels), /// Initiate a fetch in response to processing a redirection - FetchRedirect( - RequestInit, - ResponseInit, - IpcSender, - /* cancel_chan */ Option>, - ), + FetchRedirect(RequestInit, ResponseInit, IpcSender, /* cancel_chan */ Option>), /// Store a cookie for a given originating URL SetCookieForUrl(ServoUrl, Serde>, CookieSource), /// Store a set of cookies for a given originating URL @@ -370,11 +363,7 @@ pub enum CoreResourceMsg { /// Retrieve the stored cookies for a given URL GetCookiesForUrl(ServoUrl, IpcSender>, CookieSource), /// Get a cookie by name for a given originating URL - GetCookiesDataForUrl( - ServoUrl, - IpcSender>>>, - CookieSource, - ), + GetCookiesDataForUrl(ServoUrl, IpcSender>>>, CookieSource), /// Get a history state by a given history state id GetHistoryState(HistoryStateId, IpcSender>>), /// Set a history state for a given history state id @@ -394,23 +383,16 @@ pub enum CoreResourceMsg { /// Instruct the resource thread to make a new request. pub fn fetch_async(request: RequestInit, core_resource_thread: &CoreResourceThread, f: F) -where - F: Fn(FetchResponseMsg) + Send + 'static, + where F: Fn(FetchResponseMsg) + Send + 'static, { let (action_sender, action_receiver) = ipc::channel().unwrap(); - ROUTER.add_route( - action_receiver.to_opaque(), - Box::new(move |message| f(message.to().unwrap())), - ); - core_resource_thread - .send(CoreResourceMsg::Fetch( - request, - FetchChannels::ResponseMsg(action_sender, None), - )) - .unwrap(); + ROUTER.add_route(action_receiver.to_opaque(), + Box::new(move |message| f(message.to().unwrap()))); + core_resource_thread.send( + CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap(); } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct ResourceCorsData { /// CORS Preflight flag pub preflight: bool, @@ -419,7 +401,7 @@ pub struct ResourceCorsData { } /// Metadata about a loaded resource, such as is obtained from HTTP headers. -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct Metadata { /// Final URL after redirects. pub final_url: ServoUrl, @@ -436,7 +418,7 @@ pub struct Metadata { #[ignore_malloc_size_of = "Defined in hyper"] /// Headers - pub headers: Option>, + pub headers: Option>, /// HTTP Status pub status: Option<(u16, Vec)>, @@ -471,18 +453,16 @@ impl Metadata { /// Extract the parts of a Mime that we care about. pub fn set_content_type(&mut self, content_type: Option<&Mime>) { if self.headers.is_none() { - self.headers = Some(Serde(HeaderMap::new())); + self.headers = Some(Serde(Headers::new())); } if let Some(mime) = content_type { - self.headers - .as_mut() - .unwrap() - .typed_insert(ContentType::from(mime.clone())); - self.content_type = Some(Serde(ContentType::from(mime.clone()))); - for (name, value) in mime.params() { - if mime::CHARSET == name { - self.charset = Some(value.to_string()); + self.headers.as_mut().unwrap().set(ContentType(mime.clone())); + self.content_type = Some(Serde(ContentType(mime.clone()))); + let Mime(_, _, ref parameters) = *mime; + for &(ref k, ref v) in parameters { + if Attr::Charset == *k { + self.charset = Some(v.to_string()); } } } @@ -490,7 +470,7 @@ impl Metadata { } /// The creator of a given cookie -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum CookieSource { /// An HTTP API HTTP, @@ -499,23 +479,19 @@ pub enum CookieSource { } /// Convenience function for synchronously loading a whole resource. -pub fn load_whole_resource( - request: RequestInit, - core_resource_thread: &CoreResourceThread, -) -> Result<(Metadata, Vec), NetworkError> { +pub fn load_whole_resource(request: RequestInit, + core_resource_thread: &CoreResourceThread) + -> Result<(Metadata, Vec), NetworkError> { let (action_sender, action_receiver) = ipc::channel().unwrap(); - core_resource_thread - .send(CoreResourceMsg::Fetch( - request, - FetchChannels::ResponseMsg(action_sender, None), - )) - .unwrap(); + core_resource_thread.send( + CoreResourceMsg::Fetch(request, FetchChannels::ResponseMsg(action_sender, None))).unwrap(); let mut buf = vec![]; let mut metadata = None; loop { match action_receiver.recv().unwrap() { - FetchResponseMsg::ProcessRequestBody | FetchResponseMsg::ProcessRequestEOF => (), + FetchResponseMsg::ProcessRequestBody | + FetchResponseMsg::ProcessRequestEOF => (), FetchResponseMsg::ProcessResponse(Ok(m)) => { metadata = Some(match m { FetchMetadata::Unfiltered(m) => m, @@ -541,12 +517,15 @@ pub enum NetworkError { } impl NetworkError { - pub fn from_hyper_error(error: &HyperError) -> Self { + pub fn from_hyper_error(url: &ServoUrl, error: HyperError) -> Self { + if let HyperError::Ssl(ref ssl_error) = error { + return NetworkError::from_ssl_error(url, &**ssl_error); + } NetworkError::Internal(error.description().to_owned()) } - pub fn from_http_error(error: &HttpError) -> Self { - NetworkError::Internal(error.description().to_owned()) + pub fn from_ssl_error(url: &ServoUrl, error: &Error) -> Self { + NetworkError::SslValidation(url.clone(), error.description().to_owned()) } } @@ -571,16 +550,3 @@ pub fn trim_http_whitespace(mut slice: &[u8]) -> &[u8] { slice } - -pub fn http_percent_encode(bytes: &[u8]) -> String { - define_encode_set! { - // This encode set is used for HTTP header values and is defined at - // https://tools.ietf.org/html/rfc5987#section-3.2 - pub HTTP_VALUE = [percent_encoding::SIMPLE_ENCODE_SET] | { - ' ', '"', '%', '\'', '(', ')', '*', ',', '/', ':', ';', '<', '-', '>', '?', - '[', '\\', ']', '{', '}' - } - } - - url::percent_encoding::percent_encode(bytes, HTTP_VALUE).to_string() -} diff --git a/components/net_traits/pub_domains.rs b/components/net_traits/pub_domains.rs index 636790f8ea40..afe700238568 100644 --- a/components/net_traits/pub_domains.rs +++ b/components/net_traits/pub_domains.rs @@ -32,8 +32,7 @@ lazy_static! { impl<'a> FromIterator<&'a str> for PubDomainRules { fn from_iter(iter: T) -> Self - where - T: IntoIterator, + where T: IntoIterator, { let mut result = PubDomainRules::new(); for item in iter { @@ -58,8 +57,7 @@ impl PubDomainRules { } } pub fn parse(content: &str) -> PubDomainRules { - content - .lines() + content.lines() .map(str::trim) .filter(|s| !s.is_empty()) .filter(|s| !s.starts_with("//")) @@ -101,7 +99,7 @@ impl PubDomainRules { None => !domain.is_empty(), Some(index) => { !self.exceptions.contains(domain) && self.wildcards.contains(&domain[index + 1..]) || - self.rules.contains(domain) + self.rules.contains(domain) }, } } @@ -114,9 +112,8 @@ impl PubDomainRules { None => false, Some(index) => { self.exceptions.contains(domain) || - !self.wildcards.contains(&domain[index + 1..]) && - !self.rules.contains(domain) && - self.is_public_suffix(&domain[index + 1..]) + !self.wildcards.contains(&domain[index + 1..]) && !self.rules.contains(domain) && + self.is_public_suffix(&domain[index + 1..]) }, } } @@ -148,9 +145,7 @@ pub fn is_reg_domain(domain: &str) -> bool { /// Leaves the host name alone if it is an IP address. pub fn reg_host(url: &ServoUrl) -> Option { match url.origin() { - ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => { - Some(Host::Domain(String::from(reg_suffix(&*domain)))) - }, + ImmutableOrigin::Tuple(_, Host::Domain(domain), _) => Some(Host::Domain(String::from(reg_suffix(&*domain)))), ImmutableOrigin::Tuple(_, ip, _) => Some(ip), ImmutableOrigin::Opaque(_) => None, } diff --git a/components/net_traits/quality.rs b/components/net_traits/quality.rs deleted file mode 100644 index 6543cb11e8d6..000000000000 --- a/components/net_traits/quality.rs +++ /dev/null @@ -1,86 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -//TODO(eijebong): Remove this once typed headers figure out quality -// This is copy pasted from the old hyper headers to avoid hardcoding everything -// (I would probably also make some silly mistakes while migrating...) - -use http::header::HeaderValue; -use mime::Mime; -use std::{fmt, str}; - -/// A quality value, as specified in [RFC7231]. -/// -/// Quality values are decimal numbers between 0 and 1 (inclusive) with up to 3 fractional digits of precision. -/// -/// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3.1 -#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] -pub struct Quality(u16); - -impl Quality { - /// Creates a quality value from a value between 0 and 1000 inclusive. - /// - /// This is semantically divided by 1000 to produce a value between 0 and 1. - /// - /// # Panics - /// - /// Panics if the value is greater than 1000. - pub fn from_u16(quality: u16) -> Quality { - assert!(quality <= 1000); - Quality(quality) - } -} - -/// A value paired with its "quality" as defined in [RFC7231]. -/// -/// Quality items are used in content negotiation headers such as `Accept` and `Accept-Encoding`. -/// -/// [RFC7231]: https://tools.ietf.org/html/rfc7231#section-5.3 -#[derive(Clone, Debug, PartialEq)] -pub struct QualityItem { - pub item: T, - pub quality: Quality, -} - -impl QualityItem { - /// Creates a new quality item. - pub fn new(item: T, quality: Quality) -> QualityItem { - QualityItem { item, quality } - } -} - -impl fmt::Display for QualityItem -where - T: fmt::Display, -{ - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.item, fmt)?; - match self.quality.0 { - 1000 => Ok(()), - 0 => fmt.write_str("; q=0"), - mut x => { - fmt.write_str("; q=0.")?; - let mut digits = *b"000"; - digits[2] = (x % 10) as u8 + b'0'; - x /= 10; - digits[1] = (x % 10) as u8 + b'0'; - x /= 10; - digits[0] = (x % 10) as u8 + b'0'; - - let s = str::from_utf8(&digits[..]).unwrap(); - fmt.write_str(s.trim_right_matches('0')) - }, - } - } -} - -pub fn quality_to_value(q: Vec>) -> HeaderValue { - HeaderValue::from_str( - &q.iter() - .map(|q| q.to_string()) - .collect::>() - .join(", "), - ) - .unwrap() -} diff --git a/components/net_traits/request.rs b/components/net_traits/request.rs index c7d0854159d6..13120f6868a7 100644 --- a/components/net_traits/request.rs +++ b/components/net_traits/request.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::ReferrerPolicy; -use http::HeaderMap; -use hyper::Method; +use ReferrerPolicy; +use hyper::header::Headers; +use hyper::method::Method; use msg::constellation_msg::PipelineId; use servo_url::{ImmutableOrigin, ServoUrl}; use std::default::Default; @@ -20,7 +20,7 @@ pub enum Initiator { } /// A request [destination](https://fetch.spec.whatwg.org/#concept-request-destination) -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum Destination { None, Audio, @@ -46,9 +46,9 @@ impl Destination { #[inline] pub fn is_script_like(&self) -> bool { *self == Destination::Script || - *self == Destination::ServiceWorker || - *self == Destination::SharedWorker || - *self == Destination::Worker + *self == Destination::ServiceWorker || + *self == Destination::SharedWorker || + *self == Destination::Worker } } @@ -60,7 +60,7 @@ pub enum Origin { } /// A [referer](https://fetch.spec.whatwg.org/#concept-request-referrer) -#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum Referrer { NoReferrer, /// Default referrer if nothing is specified @@ -69,17 +69,17 @@ pub enum Referrer { } /// A [request mode](https://fetch.spec.whatwg.org/#concept-request-mode) -#[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum RequestMode { Navigate, SameOrigin, NoCors, CorsMode, - WebSocket { protocols: Vec }, + WebSocket { protocols: Vec } } /// Request [credentials mode](https://fetch.spec.whatwg.org/#concept-request-credentials-mode) -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum CredentialsMode { Omit, CredentialsSameOrigin, @@ -87,7 +87,7 @@ pub enum CredentialsMode { } /// [Cache mode](https://fetch.spec.whatwg.org/#concept-request-cache-mode) -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum CacheMode { Default, NoStore, @@ -98,7 +98,7 @@ pub enum CacheMode { } /// [Service-workers mode](https://fetch.spec.whatwg.org/#request-service-workers-mode) -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum ServiceWorkersMode { All, Foreign, @@ -106,7 +106,7 @@ pub enum ServiceWorkersMode { } /// [Redirect mode](https://fetch.spec.whatwg.org/#concept-request-redirect-mode) -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, PartialEq, Serialize)] pub enum RedirectMode { Follow, Error, @@ -129,27 +129,23 @@ pub enum Window { } /// [CORS settings attribute](https://html.spec.whatwg.org/multipage/#attr-crossorigin-anonymous) -#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)] +#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)] pub enum CorsSettings { Anonymous, UseCredentials, } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct RequestInit { - #[serde( - deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize" - )] + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] #[ignore_malloc_size_of = "Defined in hyper"] pub method: Method, pub url: ServoUrl, - #[serde( - deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize" - )] + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] #[ignore_malloc_size_of = "Defined in hyper"] - pub headers: HeaderMap, + pub headers: Headers, pub unsafe_request: bool, pub body: Option>, pub service_workers_mode: ServiceWorkersMode, @@ -175,9 +171,9 @@ pub struct RequestInit { impl Default for RequestInit { fn default() -> RequestInit { RequestInit { - method: Method::GET, + method: Method::Get, url: ServoUrl::parse("about:blank").unwrap(), - headers: HeaderMap::new(), + headers: Headers::new(), unsafe_request: false, body: None, service_workers_mode: ServiceWorkersMode::All, @@ -212,7 +208,7 @@ pub struct Request { pub sandboxed_storage_area_urls: bool, /// #[ignore_malloc_size_of = "Defined in hyper"] - pub headers: HeaderMap, + pub headers: Headers, /// pub unsafe_request: bool, /// @@ -263,12 +259,15 @@ pub struct Request { } impl Request { - pub fn new(url: ServoUrl, origin: Option, pipeline_id: Option) -> Request { + pub fn new(url: ServoUrl, + origin: Option, + pipeline_id: Option) + -> Request { Request { - method: Method::GET, + method: Method::Get, local_urls_only: false, sandboxed_storage_area_urls: false, - headers: HeaderMap::new(), + headers: Headers::new(), unsafe_request: false, body: None, window: Window::Client, @@ -295,11 +294,9 @@ impl Request { } pub fn from_init(init: RequestInit) -> Request { - let mut req = Request::new( - init.url.clone(), - Some(Origin::Origin(init.origin)), - init.pipeline_id, - ); + let mut req = Request::new(init.url.clone(), + Some(Origin::Origin(init.origin)), + init.pipeline_id); req.method = init.method; req.headers = init.headers; req.unsafe_request = init.unsafe_request; @@ -353,16 +350,9 @@ impl Request { /// pub fn is_subresource_request(&self) -> bool { match self.destination { - Destination::Audio | - Destination::Font | - Destination::Image | - Destination::Manifest | - Destination::Script | - Destination::Style | - Destination::Track | - Destination::Video | - Destination::Xslt | - Destination::None => true, + Destination::Audio | Destination::Font | Destination::Image | Destination::Manifest | + Destination::Script | Destination::Style | Destination::Track | Destination::Video | + Destination::Xslt | Destination::None => true, _ => false, } } diff --git a/components/net_traits/response.rs b/components/net_traits/response.rs index 33eebc4eb663..3e2b7d0ad33e 100644 --- a/components/net_traits/response.rs +++ b/components/net_traits/response.rs @@ -4,15 +4,14 @@ //! The [Response](https://fetch.spec.whatwg.org/#responses) object //! resulting from a [fetch operation](https://fetch.spec.whatwg.org/#concept-fetch) -use crate::{FetchMetadata, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy}; -use headers_core::HeaderMapExt; -use headers_ext::{AccessControlExposeHeaders, ContentType}; -use http::{HeaderMap, StatusCode}; +use {FetchMetadata, FilteredMetadata, Metadata, NetworkError, ReferrerPolicy}; +use hyper::header::{AccessControlExposeHeaders, ContentType, Headers}; +use hyper::status::StatusCode; use hyper_serde::Serde; use servo_arc::Arc; use servo_url::ServoUrl; -use std::sync::atomic::AtomicBool; use std::sync::Mutex; +use std::sync::atomic::AtomicBool; /// [Response type](https://fetch.spec.whatwg.org/#concept-response-type) #[derive(Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)] @@ -46,11 +45,13 @@ impl ResponseBody { pub fn is_done(&self) -> bool { match *self { ResponseBody::Done(..) => true, - ResponseBody::Empty | ResponseBody::Receiving(..) => false, + ResponseBody::Empty | + ResponseBody::Receiving(..) => false, } } } + /// [Cache state](https://fetch.spec.whatwg.org/#concept-response-cache-state) #[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] pub enum CacheState { @@ -74,16 +75,13 @@ pub enum ResponseMsg { Errored, } -#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Deserialize, MallocSizeOf, Serialize)] pub struct ResponseInit { pub url: ServoUrl, - #[serde( - deserialize_with = "::hyper_serde::deserialize", - serialize_with = "::hyper_serde::serialize" - )] + #[serde(deserialize_with = "::hyper_serde::deserialize", + serialize_with = "::hyper_serde::serialize")] #[ignore_malloc_size_of = "Defined in hyper"] - pub headers: HeaderMap, - pub status_code: u16, + pub headers: Headers, pub referrer: Option, pub location_url: Option>, } @@ -97,10 +95,10 @@ pub struct Response { pub url_list: Vec, /// `None` can be considered a StatusCode of `0`. #[ignore_malloc_size_of = "Defined in hyper"] - pub status: Option<(StatusCode, String)>, + pub status: Option, pub raw_status: Option<(u16, Vec)>, #[ignore_malloc_size_of = "Defined in hyper"] - pub headers: HeaderMap, + pub headers: Headers, #[ignore_malloc_size_of = "Mutex heap size undefined"] pub body: Arc>, pub cache_state: CacheState, @@ -128,9 +126,9 @@ impl Response { termination_reason: None, url: Some(url), url_list: vec![], - status: Some((StatusCode::OK, "OK".to_string())), + status: Some(StatusCode::Ok), raw_status: Some((200, b"OK".to_vec())), - headers: HeaderMap::new(), + headers: Headers::new(), body: Arc::new(Mutex::new(ResponseBody::Empty)), cache_state: CacheState::None, https_state: HttpsState::None, @@ -149,9 +147,6 @@ impl Response { res.location_url = init.location_url; res.headers = init.headers; res.referrer = init.referrer; - res.status = StatusCode::from_u16(init.status_code) - .map(|s| (s, s.to_string())) - .ok(); res } @@ -163,7 +158,7 @@ impl Response { url_list: vec![], status: None, raw_status: None, - headers: HeaderMap::new(), + headers: Headers::new(), body: Arc::new(Mutex::new(ResponseBody::Empty)), cache_state: CacheState::None, https_state: HttpsState::None, @@ -245,43 +240,45 @@ impl Response { ResponseType::Error(..) => unreachable!(), ResponseType::Basic => { - let headers = old_headers.iter().filter(|(name, _)| { - match &*name.as_str().to_ascii_lowercase() { + let headers = old_headers.iter().filter(|header| { + match &*header.name().to_ascii_lowercase() { "set-cookie" | "set-cookie2" => false, _ => true } - }).map(|(n, v)| (n.clone(), v.clone())).collect(); + }).collect(); response.headers = headers; }, ResponseType::Cors => { - let headers = old_headers.iter().filter(|(name, _)| { - match &*name.as_str().to_ascii_lowercase() { + let access = old_headers.get::(); + let allowed_headers = access.as_ref().map(|v| &v[..]).unwrap_or(&[]); + + let headers = old_headers.iter().filter(|header| { + match &*header.name().to_ascii_lowercase() { "cache-control" | "content-language" | "content-type" | "expires" | "last-modified" | "pragma" => true, "set-cookie" | "set-cookie2" => false, header => { - let access = old_headers.typed_get::(); - let result = access - .and_then(|v| v.iter().find(|h| *header == h.as_str().to_ascii_lowercase())); + let result = + allowed_headers.iter().find(|h| *header == *h.to_ascii_lowercase()); result.is_some() } } - }).map(|(n, v)| (n.clone(), v.clone())).collect(); + }).collect(); response.headers = headers; }, ResponseType::Opaque => { response.url_list = vec![]; response.url = None; - response.headers = HeaderMap::new(); + response.headers = Headers::new(); response.status = None; response.body = Arc::new(Mutex::new(ResponseBody::Empty)); response.cache_state = CacheState::None; }, ResponseType::OpaqueRedirect => { - response.headers = HeaderMap::new(); + response.headers = Headers::new(); response.status = None; response.body = Arc::new(Mutex::new(ResponseBody::Empty)); response.cache_state = CacheState::None; @@ -294,13 +291,10 @@ impl Response { pub fn metadata(&self) -> Result { fn init_metadata(response: &Response, url: &ServoUrl) -> Metadata { let mut metadata = Metadata::default(url.clone()); - metadata.set_content_type( - response - .headers - .typed_get::() - .map(|v| v.into()) - .as_ref(), - ); + metadata.set_content_type(match response.headers.get() { + Some(&ContentType(ref mime)) => Some(mime), + None => None, + }); metadata.location_url = response.location_url.clone(); metadata.headers = Some(Serde(response.headers.clone())); metadata.status = response.raw_status.clone(); @@ -324,27 +318,26 @@ impl Response { match self.response_type { ResponseType::Basic => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Basic(metadata.unwrap()), - unsafe_: unsafe_metadata, + unsafe_: unsafe_metadata }), ResponseType::Cors => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Cors(metadata.unwrap()), - unsafe_: unsafe_metadata, + unsafe_: unsafe_metadata }), ResponseType::Default => unreachable!(), - ResponseType::Error(ref network_err) => Err(network_err.clone()), + ResponseType::Error(ref network_err) => + Err(network_err.clone()), ResponseType::Opaque => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::Opaque, - unsafe_: unsafe_metadata, + unsafe_: unsafe_metadata }), ResponseType::OpaqueRedirect => Ok(FetchMetadata::Filtered { filtered: FilteredMetadata::OpaqueRedirect, - unsafe_: unsafe_metadata, - }), + unsafe_: unsafe_metadata + }) } }, - None => Err(NetworkError::Internal( - "No url found in unsafe response".to_owned(), - )), + None => Err(NetworkError::Internal("No url found in unsafe response".to_owned())) } } else { assert_eq!(self.response_type, ResponseType::Default); diff --git a/components/net_traits/storage_thread.rs b/components/net_traits/storage_thread.rs index ec636a810a60..12047d084431 100644 --- a/components/net_traits/storage_thread.rs +++ b/components/net_traits/storage_thread.rs @@ -5,14 +5,14 @@ use ipc_channel::ipc::IpcSender; use servo_url::ServoUrl; -#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, Serialize)] +#[derive(Clone, Copy, Deserialize, MallocSizeOf, Serialize)] pub enum StorageType { Session, Local, } /// Request operations on the storage data associated with a particular url -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum StorageThreadMsg { /// gets the number of key/value pairs present in the associated storage data Length(IpcSender, ServoUrl, StorageType), @@ -27,13 +27,7 @@ pub enum StorageThreadMsg { GetItem(IpcSender>, ServoUrl, StorageType, String), /// sets the value of the given key in the associated storage data - SetItem( - IpcSender), ()>>, - ServoUrl, - StorageType, - String, - String, - ), + SetItem(IpcSender), ()>>, ServoUrl, StorageType, String, String), /// removes the key/value pair for the given key in the associated storage data RemoveItem(IpcSender>, ServoUrl, StorageType, String), diff --git a/components/net_traits/tests/image.rs b/components/net_traits/tests/image.rs index e7d2d460d7eb..238fae97050b 100644 --- a/components/net_traits/tests/image.rs +++ b/components/net_traits/tests/image.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate net_traits; + use net_traits::image::base::detect_image_format; #[test] diff --git a/components/net_traits/tests/pub_domains.rs b/components/net_traits/tests/pub_domains.rs index c17f8ba8c078..fa298633f6ca 100644 --- a/components/net_traits/tests/pub_domains.rs +++ b/components/net_traits/tests/pub_domains.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate net_traits; + use net_traits::pub_domains::{is_pub_domain, is_reg_domain, pub_suffix, reg_suffix}; // These tests may need to be updated if the PSL changes. @@ -114,9 +116,6 @@ fn test_reg_suffix() { #[test] fn test_weirdness() { // These are weird results, but AFAICT they are spec-compliant. - assert_ne!( - pub_suffix("city.yokohama.jp"), - pub_suffix(pub_suffix("city.yokohama.jp")) - ); + assert_ne!(pub_suffix("city.yokohama.jp"), pub_suffix(pub_suffix("city.yokohama.jp"))); assert!(!is_pub_domain(pub_suffix("city.yokohama.jp"))); } diff --git a/components/net_traits/tests/whitespace.rs b/components/net_traits/tests/whitespace.rs index d2bc9d1a3bea..4954e0f67f4c 100644 --- a/components/net_traits/tests/whitespace.rs +++ b/components/net_traits/tests/whitespace.rs @@ -2,6 +2,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ +extern crate net_traits; + #[test] fn test_trim_http_whitespace() { fn test_trim(in_: &[u8], out: &[u8]) { diff --git a/components/pixels/Cargo.toml b/components/pixels/Cargo.toml deleted file mode 100644 index 40f14013452a..000000000000 --- a/components/pixels/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "pixels" -version = "0.0.1" -authors = ["The Servo Project Developers"] -license = "MPL-2.0" -edition = "2018" -publish = false - -[lib] -name = "pixels" -path = "lib.rs" - -[dependencies] -euclid = "0.19" diff --git a/components/pixels/lib.rs b/components/pixels/lib.rs deleted file mode 100644 index 16c93b7b6afb..000000000000 --- a/components/pixels/lib.rs +++ /dev/null @@ -1,84 +0,0 @@ -/* This Source Code Form is subject to the terms of the Mozilla Public - * License, v. 2.0. If a copy of the MPL was not distributed with this - * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use euclid::{Point2D, Rect, Size2D}; -use std::borrow::Cow; - -pub fn get_rect(pixels: &[u8], size: Size2D, rect: Rect) -> Cow<[u8]> { - assert!(!rect.is_empty()); - assert!(Rect::from_size(size).contains_rect(&rect)); - assert_eq!(pixels.len() % 4, 0); - assert_eq!(size.area() as usize, pixels.len() / 4); - let area = rect.size.area() as usize; - let first_column_start = rect.origin.x as usize * 4; - let row_length = size.width as usize * 4; - let first_row_start = rect.origin.y as usize * row_length; - if rect.origin.x == 0 && rect.size.width == size.width || rect.size.height == 1 { - let start = first_column_start + first_row_start; - return Cow::Borrowed(&pixels[start..start + area * 4]); - } - let mut data = Vec::with_capacity(area * 4); - for row in pixels[first_row_start..] - .chunks(row_length) - .take(rect.size.height as usize) - { - data.extend_from_slice(&row[first_column_start..][..rect.size.width as usize * 4]); - } - data.into() -} - -// TODO(pcwalton): Speed up with SIMD, or better yet, find some way to not do this. -pub fn byte_swap_colors_inplace(pixels: &mut [u8]) { - assert!(pixels.len() % 4 == 0); - for rgba in pixels.chunks_mut(4) { - let b = rgba[0]; - rgba[0] = rgba[2]; - rgba[2] = b; - } -} - -pub fn byte_swap_and_premultiply_inplace(pixels: &mut [u8]) { - assert!(pixels.len() % 4 == 0); - for rgba in pixels.chunks_mut(4) { - let b = rgba[0]; - rgba[0] = multiply_u8_color(rgba[2], rgba[3]); - rgba[1] = multiply_u8_color(rgba[1], rgba[3]); - rgba[2] = multiply_u8_color(b, rgba[3]); - } -} - -/// Returns true if the pixels were found to be completely opaque. -pub fn premultiply_inplace(pixels: &mut [u8]) -> bool { - assert!(pixels.len() % 4 == 0); - let mut is_opaque = true; - for rgba in pixels.chunks_mut(4) { - rgba[0] = multiply_u8_color(rgba[0], rgba[3]); - rgba[1] = multiply_u8_color(rgba[1], rgba[3]); - rgba[2] = multiply_u8_color(rgba[2], rgba[3]); - is_opaque = is_opaque && rgba[3] == 255; - } - is_opaque -} - -pub fn multiply_u8_color(a: u8, b: u8) -> u8 { - return (a as u32 * b as u32 / 255) as u8; -} - -pub fn clip( - mut origin: Point2D, - mut size: Size2D, - surface: Size2D, -) -> Option> { - if origin.x < 0 { - size.width = size.width.saturating_sub(-origin.x as u32); - origin.x = 0; - } - if origin.y < 0 { - size.height = size.height.saturating_sub(-origin.y as u32); - origin.y = 0; - } - Rect::new(origin.to_u32(), size) - .intersection(&Rect::from_size(surface)) - .filter(|rect| !rect.is_empty()) -} diff --git a/components/profile/Cargo.toml b/components/profile/Cargo.toml index 6008c31b10ff..7b9d79a7a8f0 100644 --- a/components/profile/Cargo.toml +++ b/components/profile/Cargo.toml @@ -1,11 +1,8 @@ -cargo-features = ["rename-dependency"] - [package] name = "profile" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] @@ -13,19 +10,18 @@ name = "profile" path = "lib.rs" [features] -unstable = ["servo_allocator"] +unstable = ["jemalloc-sys"] [dependencies] profile_traits = {path = "../profile_traits"} -influent = "0.5" +influent = "0.4" ipc-channel = "0.11" heartbeats-simple = "0.4" log = "0.4" serde = "1.0" serde_json = "1.0" servo_config = {path = "../config"} -time_crate = {package = "time", version = "0.1.12"} -tokio = "0.1" +time = "0.1.12" [target.'cfg(target_os = "macos")'.dependencies] task_info = {path = "../../support/rust-task_info"} @@ -35,4 +31,4 @@ regex = "1.0" [target.'cfg(not(target_os = "windows"))'.dependencies] libc = "0.2" -servo_allocator = {path = "../allocator", optional = true} +jemalloc-sys = {version = "0.1.3", optional = true} diff --git a/components/profile/heartbeats.rs b/components/profile/heartbeats.rs index 4bdd5fd7527f..ef95c853fce9 100644 --- a/components/profile/heartbeats.rs +++ b/components/profile/heartbeats.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use self::synchronized_heartbeat::{heartbeat_window_callback, lock_and_work}; use heartbeats_simple::HeartbeatPow as Heartbeat; use profile_traits::time::ProfilerCategory; +use self::synchronized_heartbeat::{heartbeat_window_callback, lock_and_work}; use servo_config::opts; use std::collections::HashMap; use std::env::var_os; @@ -139,12 +139,12 @@ fn log_heartbeat_records(hb: &mut Heartbeat) { } mod synchronized_heartbeat { - use super::log_heartbeat_records; use heartbeats_simple::HeartbeatPow as Heartbeat; use heartbeats_simple::HeartbeatPowContext as HeartbeatContext; use profile_traits::time::ProfilerCategory; use std::collections::HashMap; - use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; + use std::sync::atomic::{ATOMIC_BOOL_INIT, AtomicBool, Ordering}; + use super::log_heartbeat_records; static mut HBS: Option<*mut HashMap> = None; diff --git a/components/profile/lib.rs b/components/profile/lib.rs index b9c6085be469..d01aad61cd05 100644 --- a/components/profile/lib.rs +++ b/components/profile/lib.rs @@ -4,12 +4,27 @@ #![deny(unsafe_code)] +#[allow(unused_extern_crates)] +extern crate heartbeats_simple; +extern crate influent; +extern crate ipc_channel; +#[cfg(all(feature = "unstable", not(target_os = "windows")))] +extern crate jemalloc_sys; +#[cfg(not(target_os = "windows"))] +extern crate libc; #[macro_use] extern crate log; #[macro_use] extern crate profile_traits; +#[cfg(target_os = "linux")] +extern crate regex; #[macro_use] extern crate serde; +extern crate serde_json; +extern crate servo_config; +#[cfg(target_os = "macos")] +extern crate task_info; +extern crate time as std_time; #[allow(unsafe_code)] mod heartbeats; diff --git a/components/profile/mem.rs b/components/profile/mem.rs index 7c60ba07b67b..2f2cda218474 100644 --- a/components/profile/mem.rs +++ b/components/profile/mem.rs @@ -4,16 +4,16 @@ //! Memory profiling functions. -use crate::time::duration_from_seconds; use ipc_channel::ipc::{self, IpcReceiver}; use ipc_channel::router::ROUTER; -use profile_traits::mem::ReportsChan; use profile_traits::mem::{ProfilerChan, ProfilerMsg, ReportKind, Reporter, ReporterRequest}; +use profile_traits::mem::ReportsChan; use std::borrow::ToOwned; use std::cmp::Ordering; use std::collections::HashMap; use std::thread; use std::time::Instant; +use time::duration_from_seconds; pub struct Profiler { /// The port through which messages are received. @@ -43,8 +43,7 @@ impl Profiler { if chan.send(ProfilerMsg::Print).is_err() { break; } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } // Always spawn the memory profiler. If there is no timer thread it won't receive regular @@ -54,8 +53,7 @@ impl Profiler { .spawn(move || { let mut mem_profiler = Profiler::new(port); mem_profiler.start(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); let mem_profiler_chan = ProfilerChan(chan); @@ -386,11 +384,10 @@ impl ReportsForest { //--------------------------------------------------------------------------- mod system_reporter { - use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; - #[cfg(target_os = "linux")] - use libc::c_int; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use libc::{c_void, size_t}; + #[cfg(target_os = "linux")] + use libc::c_int; use profile_traits::mem::{Report, ReportKind, ReporterRequest}; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ffi::CString; @@ -398,8 +395,9 @@ mod system_reporter { use std::mem::size_of; #[cfg(all(feature = "unstable", not(target_os = "windows")))] use std::ptr::null_mut; + use super::{JEMALLOC_HEAP_ALLOCATED_STR, SYSTEM_HEAP_ALLOCATED_STR}; #[cfg(target_os = "macos")] - use task_info::task_basic_info::{resident_size, virtual_size}; + use task_info::task_basic_info::{virtual_size, resident_size}; /// Collects global measurements from the OS and heap allocators. pub fn collect_reports(request: ReporterRequest) { @@ -496,7 +494,7 @@ mod system_reporter { } #[cfg(all(feature = "unstable", not(target_os = "windows")))] - use servo_allocator::jemalloc_sys::mallctl; + use jemalloc_sys::mallctl; #[cfg(all(feature = "unstable", not(target_os = "windows")))] fn jemalloc_stat(value_name: &str) -> Option { @@ -601,10 +599,10 @@ mod system_reporter { #[cfg(target_os = "linux")] fn resident_segments() -> Vec<(String, usize)> { use regex::Regex; - use std::collections::hash_map::Entry; use std::collections::HashMap; + use std::collections::hash_map::Entry; use std::fs::File; - use std::io::{BufRead, BufReader}; + use std::io::{BufReader, BufRead}; // The first line of an entry in /proc//smaps looks just like an entry // in /proc//maps: @@ -625,8 +623,7 @@ mod system_reporter { let seg_re = Regex::new( r"^[:xdigit:]+-[:xdigit:]+ (....) [:xdigit:]+ [:xdigit:]+:[:xdigit:]+ \d+ +(.*)", - ) - .unwrap(); + ).unwrap(); let rss_re = Regex::new(r"^Rss: +(\d+) kB").unwrap(); // We record each segment's resident size. diff --git a/components/profile/time.rs b/components/profile/time.rs index a2dd71e605a6..780a6e9da2fd 100644 --- a/components/profile/time.rs +++ b/components/profile/time.rs @@ -4,18 +4,16 @@ //! Timing functions. -use crate::heartbeats; -use crate::trace_dump::TraceDump; +use heartbeats; use influent::client::{Client, Credentials}; use influent::create_client; use influent::measurement::{Measurement, Value}; use ipc_channel::ipc::{self, IpcReceiver}; use profile_traits::energy::{energy_interval_ms, read_energy_uj}; -use profile_traits::time::{ - ProfilerCategory, ProfilerChan, ProfilerData, ProfilerMsg, TimerMetadata, -}; +use profile_traits::time::{ProfilerCategory, ProfilerChan, ProfilerMsg, ProfilerData, TimerMetadata}; use profile_traits::time::{TimerMetadataFrameType, TimerMetadataReflowType}; use servo_config::opts::OutputOptions; +use std::{f64, thread, u32, u64}; use std::borrow::ToOwned; use std::cmp::Ordering; use std::collections::BTreeMap; @@ -24,9 +22,8 @@ use std::fs::File; use std::io::{self, Write}; use std::path::Path; use std::time::Duration; -use std::{f64, thread, u32, u64}; -use time_crate::precise_time_ns; -use tokio::prelude::Future; +use std_time::precise_time_ns; +use trace_dump::TraceDump; pub trait Formattable { fn format(&self, output: &Option) -> String; @@ -185,8 +182,7 @@ impl Profiler { let trace = file_path.as_ref().and_then(|p| TraceDump::new(p).ok()); let mut profiler = Profiler::new(port, trace, Some(outputoption)); profiler.start(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); // decide if we need to spawn the timer thread match option { &OutputOptions::FileName(_) | &OutputOptions::DB(_, _, _, _) => { @@ -202,8 +198,7 @@ impl Profiler { if chan.send(ProfilerMsg::Print).is_err() { break; } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); }, } }, @@ -217,8 +212,7 @@ impl Profiler { let trace = file_path.as_ref().and_then(|p| TraceDump::new(p).ok()); let mut profiler = Profiler::new(port, trace, None); profiler.start(); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } else { // No-op to handle messages when the time profiler is not printing: thread::Builder::new() @@ -232,8 +226,7 @@ impl Profiler { }, _ => {}, } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } }, } @@ -286,8 +279,7 @@ impl Profiler { start_time = end_time; start_energy = end_energy; } - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } profiler_chan @@ -329,11 +321,9 @@ impl Profiler { let ms = (t.1 - t.0) as f64 / 1000000f64; self.find_or_insert(k, ms); }, - ProfilerMsg::Print => { - if let Some(ProfilerMsg::Time(..)) = self.last_msg { - // only print if more data has arrived since the last printout - self.print_buckets(); - } + ProfilerMsg::Print => if let Some(ProfilerMsg::Time(..)) = self.last_msg { + // only print if more data has arrived since the last printout + self.print_buckets(); }, ProfilerMsg::Get(k, sender) => { let vec_option = self.buckets.get(&k); @@ -389,8 +379,7 @@ impl Profiler { file, "_category_\t_incremental?_\t_iframe?_\t_url_\t_mean (ms)_\t\ _median (ms)_\t_min (ms)_\t_max (ms)_\t_events_\n" - ) - .unwrap(); + ).unwrap(); for (&(ref category, ref meta), ref mut data) in &mut self.buckets { data.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values in profiles")); let data_len = data.len(); @@ -406,8 +395,7 @@ impl Profiler { min, max, data_len - ) - .unwrap(); + ).unwrap(); } } }, @@ -427,8 +415,7 @@ impl Profiler { " _min (ms)_", " _max (ms)_", " _events_" - ) - .unwrap(); + ).unwrap(); for (&(ref category, ref meta), ref mut data) in &mut self.buckets { data.sort_by(|a, b| a.partial_cmp(b).expect("No NaN values in profiles")); let data_len = data.len(); @@ -444,8 +431,7 @@ impl Profiler { min, max, data_len - ) - .unwrap(); + ).unwrap(); } } writeln!(&mut lock, "").unwrap(); @@ -484,10 +470,9 @@ impl Profiler { if let Some(ref meta) = *meta { measurement.add_tag("host", meta.url.as_str()); }; - - tokio::run(client.write_one(measurement, None).map_err(|e| { - warn!("Could not write measurement to profiler db: {:?}", e) - })); + if client.write_one(measurement, None).is_err() { + warn!("Could not write measurement to profiler db"); + } } } }, diff --git a/components/profile/trace_dump.rs b/components/profile/trace_dump.rs index ad2e0eccc266..4654f4dfb578 100644 --- a/components/profile/trace_dump.rs +++ b/components/profile/trace_dump.rs @@ -5,6 +5,7 @@ //! A module for writing time profiler traces out to a self contained HTML file. use profile_traits::time::{ProfilerCategory, TimerMetadata}; +use serde_json; use std::fs; use std::io::{self, Write}; use std::path; diff --git a/components/profile_traits/Cargo.toml b/components/profile_traits/Cargo.toml index 28553f59de06..ca9ce8aece6b 100644 --- a/components/profile_traits/Cargo.toml +++ b/components/profile_traits/Cargo.toml @@ -3,7 +3,6 @@ name = "profile_traits" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/profile_traits/ipc.rs b/components/profile_traits/ipc.rs index 0e1fae123a87..7436ef5d5f15 100644 --- a/components/profile_traits/ipc.rs +++ b/components/profile_traits/ipc.rs @@ -2,12 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::time; -use crate::time::ProfilerCategory; -use crate::time::ProfilerChan; +use bincode; use ipc_channel::ipc; use serde::{Deserialize, Serialize}; use std::io::Error; +use time; +use time::ProfilerCategory; +use time::ProfilerChan; pub struct IpcReceiver where @@ -53,12 +54,14 @@ where Ok((ipc_sender, profiled_ipc_receiver)) } -pub struct IpcBytesReceiver { +pub struct IpcBytesReceiver +{ ipc_bytes_receiver: ipc::IpcBytesReceiver, time_profile_chan: ProfilerChan, } -impl IpcBytesReceiver { +impl IpcBytesReceiver +{ pub fn recv(&self) -> Result, bincode::Error> { time::profile( ProfilerCategory::IpcBytesReceiver, @@ -71,7 +74,8 @@ impl IpcBytesReceiver { pub fn bytes_channel( time_profile_chan: ProfilerChan, -) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> { +) -> Result<(ipc::IpcBytesSender, IpcBytesReceiver), Error> +{ let (ipc_bytes_sender, ipc_bytes_receiver) = ipc::bytes_channel()?; let profiled_ipc_bytes_receiver = IpcBytesReceiver { ipc_bytes_receiver, diff --git a/components/profile_traits/lib.rs b/components/profile_traits/lib.rs index cf7034d5962d..017d35b24c1a 100644 --- a/components/profile_traits/lib.rs +++ b/components/profile_traits/lib.rs @@ -8,10 +8,15 @@ #![deny(unsafe_code)] +extern crate bincode; +extern crate ipc_channel; #[macro_use] extern crate log; #[macro_use] extern crate serde; +extern crate servo_channel; +extern crate servo_config; +extern crate signpost; #[allow(unsafe_code)] pub mod energy; diff --git a/components/profile_traits/mem.rs b/components/profile_traits/mem.rs index 7b90a1274d3d..b40d8a855864 100644 --- a/components/profile_traits/mem.rs +++ b/components/profile_traits/mem.rs @@ -8,6 +8,7 @@ use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; +use serde; use servo_channel::Sender; use std::marker::Send; @@ -44,7 +45,7 @@ where /// Front-end representation of the profiler used to communicate with the /// profiler. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender); impl ProfilerChan { @@ -101,7 +102,7 @@ impl ProfilerChan { /// and thread stacks. "explicit" is not guaranteed to cover every explicit allocation, but it does /// cover most (including the entire heap), and therefore it is the single best number to focus on /// when trying to reduce memory usage. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum ReportKind { /// A size measurement for an explicit allocation on the jemalloc heap. This should be used /// for any measurements done via the `MallocSizeOf` trait. @@ -125,7 +126,7 @@ pub enum ReportKind { } /// A single memory-related measurement. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct Report { /// The identifying path for this report. pub path: Vec, @@ -138,7 +139,7 @@ pub struct Report { } /// A channel through which memory reports can be sent. -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ReportsChan(pub IpcSender>); impl ReportsChan { @@ -151,7 +152,7 @@ impl ReportsChan { } /// The protocol used to send reporter requests. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct ReporterRequest { /// The channel on which reports are to be sent. pub reports_channel: ReportsChan, @@ -164,7 +165,7 @@ pub struct ReporterRequest { /// In many cases, clients construct `Reporter` objects by creating an IPC sender/receiver pair and /// registering the receiving end with the router so that messages from the memory profiler end up /// injected into the client's event loop. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub struct Reporter(pub IpcSender); impl Reporter { @@ -173,8 +174,7 @@ impl Reporter { self.0 .send(ReporterRequest { reports_channel: reports_chan, - }) - .unwrap() + }).unwrap() } } @@ -188,7 +188,7 @@ macro_rules! path { } /// Messages that can be sent to the memory profiler thread. -#[derive(Debug, Deserialize, Serialize)] +#[derive(Deserialize, Serialize)] pub enum ProfilerMsg { /// Register a Reporter with the memory profiler. The String is only used to identify the /// reporter so it can be unregistered later. The String must be distinct from that used by any diff --git a/components/profile_traits/time.rs b/components/profile_traits/time.rs index 1107099f91b8..9f3c41740ff4 100644 --- a/components/profile_traits/time.rs +++ b/components/profile_traits/time.rs @@ -2,10 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::energy::read_energy_uj; +extern crate time as std_time; + +use energy::read_energy_uj; use ipc_channel::ipc::IpcSender; +use self::std_time::precise_time_ns; use servo_config::opts; -use time::precise_time_ns; +use signpost; #[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)] pub struct TimerMetadata { @@ -14,7 +17,7 @@ pub struct TimerMetadata { pub incremental: TimerMetadataReflowType, } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub struct ProfilerChan(pub IpcSender); impl ProfilerChan { @@ -25,13 +28,13 @@ impl ProfilerChan { } } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum ProfilerData { NoRecords, Record(Vec), } -#[derive(Clone, Debug, Deserialize, Serialize)] +#[derive(Clone, Deserialize, Serialize)] pub enum ProfilerMsg { /// Normal message used for reporting time Time( diff --git a/components/rand/Cargo.toml b/components/rand/Cargo.toml index e41309fe56eb..56e34c6ec27b 100644 --- a/components/rand/Cargo.toml +++ b/components/rand/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_rand" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/rand/lib.rs b/components/rand/lib.rs index 54c0de6d5015..5a10bf9e3c1e 100644 --- a/components/rand/lib.rs +++ b/components/rand/lib.rs @@ -16,14 +16,16 @@ extern crate lazy_static; #[macro_use] extern crate log; +extern crate rand; +extern crate uuid; +pub use rand::{Rand, Rng, SeedableRng}; #[cfg(target_pointer_width = "64")] use rand::isaac::Isaac64Rng as IsaacWordRng; #[cfg(target_pointer_width = "32")] use rand::isaac::IsaacRng as IsaacWordRng; use rand::os::OsRng; -use rand::reseeding::{Reseeder, ReseedingRng}; -pub use rand::{Rand, Rng, SeedableRng}; +use rand::reseeding::{ReseedingRng, Reseeder}; use std::cell::RefCell; use std::mem; use std::rc::Rc; diff --git a/components/range/Cargo.toml b/components/range/Cargo.toml index 8aa28cf82639..9786f7824f7c 100644 --- a/components/range/Cargo.toml +++ b/components/range/Cargo.toml @@ -4,7 +4,6 @@ name = "range" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/range/lib.rs b/components/range/lib.rs index 797ba4b9b832..9d65a2297174 100644 --- a/components/range/lib.rs +++ b/components/range/lib.rs @@ -4,8 +4,10 @@ #![deny(unsafe_code)] +extern crate malloc_size_of; #[macro_use] extern crate malloc_size_of_derive; +extern crate num_traits; #[macro_use] extern crate serde; diff --git a/components/remutex/Cargo.toml b/components/remutex/Cargo.toml index 94d3ebb4c38d..4f471f5378da 100644 --- a/components/remutex/Cargo.toml +++ b/components/remutex/Cargo.toml @@ -3,7 +3,6 @@ name = "servo_remutex" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false [lib] diff --git a/components/remutex/lib.rs b/components/remutex/lib.rs index d47237d0ef6f..6f8f11ac498d 100644 --- a/components/remutex/lib.rs +++ b/components/remutex/lib.rs @@ -18,8 +18,8 @@ extern crate log; use std::cell::{Cell, UnsafeCell}; use std::num::NonZeroUsize; use std::ops::Deref; -use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{LockResult, Mutex, MutexGuard, PoisonError, TryLockError, TryLockResult}; +use std::sync::atomic::{AtomicUsize, Ordering}; /// A type for thread ids. diff --git a/components/remutex/tests/smoke.rs b/components/remutex/tests/smoke.rs index 5c095ea703f1..31ac9d48402d 100644 --- a/components/remutex/tests/smoke.rs +++ b/components/remutex/tests/smoke.rs @@ -10,6 +10,8 @@ // These tests came from https://github.com/rust-lang/rust/blob/master/src/libstd/sys/common/remutex.rs +extern crate servo_remutex; + use servo_remutex::{ReentrantMutex, ReentrantMutexGuard}; use std::cell::RefCell; use std::sync::Arc; @@ -58,8 +60,7 @@ fn trylock_works() { thread::spawn(move || { let lock = m2.try_lock(); assert!(lock.is_err()); - }) - .join() + }).join() .unwrap(); let _lock3 = m.try_lock().unwrap(); } @@ -83,8 +84,7 @@ fn poison_works() { let _answer = Answer(lock2); println!("Intentionally panicking."); panic!("What the answer to my lifetimes dilemma is?"); - }) - .join(); + }).join(); assert!(result.is_err()); let r = m.lock().err().unwrap().into_inner(); assert_eq!(*r.borrow(), 42); diff --git a/components/script/Cargo.toml b/components/script/Cargo.toml index f2fd91df9bbf..ca859bb472a5 100644 --- a/components/script/Cargo.toml +++ b/components/script/Cargo.toml @@ -1,11 +1,8 @@ -cargo-features = ["rename-dependency"] - [package] name = "script" version = "0.0.1" authors = ["The Servo Project Developers"] license = "MPL-2.0" -edition = "2018" publish = false build = "build.rs" @@ -15,7 +12,7 @@ name = "script" path = "lib.rs" [features] -debugmozjs = ['js/debugmozjs'] +debugmozjs = ['mozjs/debugmozjs'] unstable = [] unrooted_must_root_lint = ["script_plugins/unrooted_must_root_lint"] default = ["unrooted_must_root_lint"] @@ -33,16 +30,17 @@ tinyfiledialogs = "3.0" [dependencies] app_units = "0.7" +audio-video-metadata = "0.1.4" backtrace = {version = "0.3", optional = true} -base64 = "0.9" +base64 = "0.6" bitflags = "1.0" bluetooth_traits = {path = "../bluetooth_traits"} byteorder = "1.0" canvas_traits = {path = "../canvas_traits"} caseless = "0.2" -cookie = "0.11" +cookie = "0.10" chrono = "0.4" -cssparser = "0.25" +cssparser = "0.24" deny_public_fields = {path = "../deny_public_fields"} devtools_traits = {path = "../devtools_traits"} dom_struct = {path = "../dom_struct"} @@ -54,18 +52,13 @@ euclid = "0.19" fnv = "1.0" gleam = "0.6" half = "1.0" -headers-core = "0.0.1" -headers-ext = "0.0.3" html5ever = "0.22" -http = "0.1" -hyper = "0.12" -hyper_serde = "0.9" +hyper = "0.10" +hyper_serde = "0.8" image = "0.19" ipc-channel = "0.11" itertools = "0.7.6" -js = {package = "mozjs", version = "0.9.3"} jstraceable_derive = {path = "../jstraceable_derive"} -keyboard-types = {version = "0.4.2-servo", features = ["serde"]} lazy_static = "1" libc = "0.2" log = "0.4" @@ -73,15 +66,15 @@ malloc_size_of = { path = "../malloc_size_of" } malloc_size_of_derive = { path = "../malloc_size_of_derive" } metrics = {path = "../metrics"} mitochondria = "1.1.2" -mime = "0.3" -mime_guess = "2.0.0-alpha.6" +mime = "0.2.1" +mime_guess = "1.8.0" +mozjs = "0.9.0" msg = {path = "../msg"} net_traits = {path = "../net_traits"} num-traits = "0.2" offscreen_gl_context = {version = "0.21", features = ["serde"]} parking_lot = "0.6" phf = "0.7.18" -pixels = {path = "../pixels"} profile_traits = {path = "../profile_traits"} ref_filter_map = "1.0.1" ref_slice = "1.0" @@ -116,3 +109,6 @@ webvr_traits = {path = "../webvr_traits"} [target.'cfg(not(target_os = "ios"))'.dependencies] mozangle = "0.1" + +[dev-dependencies] +embedder_traits = { path = "../embedder_traits", features = ["tests"] } diff --git a/components/script/body.rs b/components/script/body.rs index 60ab96fd1b0f..9709043912b4 100644 --- a/components/script/body.rs +++ b/components/script/body.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::USVString; -use crate::dom::bindings::trace::RootedTraceableBox; -use crate::dom::blob::{Blob, BlobImpl}; -use crate::dom::formdata::FormData; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::DomRoot; +use dom::bindings::str::USVString; +use dom::bindings::trace::RootedTraceableBox; +use dom::blob::{Blob, BlobImpl}; +use dom::formdata::FormData; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use js::jsapi::Heap; use js::jsapi::JSContext; use js::jsapi::JSObject; @@ -22,7 +22,7 @@ use js::jsval::UndefinedValue; use js::rust::wrappers::JS_GetPendingException; use js::rust::wrappers::JS_ParseJSON; use js::typedarray::{ArrayBuffer, CreateWith}; -use mime::{self, Mime}; +use mime::{Mime, TopLevel, SubLevel}; use std::cell::Ref; use std::ptr; use std::rc::Rc; @@ -178,20 +178,20 @@ fn run_form_data_algorithm( let mime: Mime = mime_str .parse() .map_err(|_| Error::Type("Inappropriate MIME-type for Body".to_string()))?; - - // TODO - // ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) - // ... is not fully determined yet. - if mime.type_() == mime::APPLICATION && mime.subtype() == mime::WWW_FORM_URLENCODED { - let entries = form_urlencoded::parse(&bytes); - let formdata = FormData::new(None, root); - for (k, e) in entries { - formdata.Append(USVString(k.into_owned()), USVString(e.into_owned())); - } - return Ok(FetchedData::FormData(formdata)); + match mime { + // TODO + // ... Parser for Mime(TopLevel::Multipart, SubLevel::FormData, _) + // ... is not fully determined yet. + Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) => { + let entries = form_urlencoded::parse(&bytes); + let formdata = FormData::new(None, root); + for (k, e) in entries { + formdata.Append(USVString(k.into_owned()), USVString(e.into_owned())); + } + return Ok(FetchedData::FormData(formdata)); + }, + _ => return Err(Error::Type("Inappropriate MIME-type for Body".to_string())), } - - Err(Error::Type("Inappropriate MIME-type for Body".to_string())) } #[allow(unsafe_code)] diff --git a/components/script/build.rs b/components/script/build.rs index a12503d67f72..d801137c59c7 100644 --- a/components/script/build.rs +++ b/components/script/build.rs @@ -2,8 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use phf_shared; -use serde_json::{self, Value}; +extern crate cmake; +extern crate phf_codegen; +extern crate phf_shared; +extern crate serde_json; + +use serde_json::Value; use std::env; use std::fmt; use std::fs::File; @@ -65,8 +69,7 @@ fn main() { write!( &mut phf, "pub static MAP: phf::Map<&'static [u8], unsafe fn(*mut JSContext, HandleObject)> = " - ) - .unwrap(); + ).unwrap(); map.build(&mut phf).unwrap(); write!(&mut phf, ";\n").unwrap(); } @@ -76,10 +79,9 @@ struct Bytes<'a>(&'a str); impl<'a> fmt::Debug for Bytes<'a> { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - // https://github.com/rust-lang/rust/issues/55223 - // should technically be just `write!(formatter, "b\"{}\"", self.0) - // but the referenced issue breaks promotion in the surrounding code - write!(formatter, "{{ const FOO: &[u8] = b\"{}\"; FOO }}", self.0) + formatter.write_str("b\"")?; + formatter.write_str(self.0)?; + formatter.write_str("\" as &'static [u8]") } } diff --git a/components/script/clipboard_provider.rs b/components/script/clipboard_provider.rs index 9ae2bdaa6ea0..86e9139895a6 100644 --- a/components/script/clipboard_provider.rs +++ b/components/script/clipboard_provider.rs @@ -3,14 +3,14 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use ipc_channel::ipc::channel; -use script_traits::{ScriptMsg, ScriptToConstellationChan}; +use script_traits::{ScriptToConstellationChan, ScriptMsg}; use std::borrow::ToOwned; pub trait ClipboardProvider { // blocking method to get the clipboard contents fn clipboard_contents(&mut self) -> String; // blocking method to set the clipboard contents - fn set_clipboard_contents(&mut self, _: String); + fn set_clipboard_contents(&mut self, String); } impl ClipboardProvider for ScriptToConstellationChan { diff --git a/components/script/devtools.rs b/components/script/devtools.rs index ddc5528ecc4f..6f28c1112158 100644 --- a/components/script/devtools.rs +++ b/components/script/devtools.rs @@ -2,31 +2,31 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods; -use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; -use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::conversions::{jsstring_to_str, ConversionResult, FromJSValConvertible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::AnimationFrameCallback; -use crate::dom::element::Element; -use crate::dom::globalscope::GlobalScope; -use crate::dom::node::{window_from_node, Node}; -use crate::dom::window::Window; -use crate::script_thread::Documents; -use devtools_traits::TimelineMarkerType; use devtools_traits::{AutoMargins, CachedConsoleMessage, CachedConsoleMessageTypes}; use devtools_traits::{ComputedNodeLayout, ConsoleAPI, PageError}; use devtools_traits::{EvaluateJSReply, Modification, NodeInfo, TimelineMarker}; +use devtools_traits::TimelineMarkerType; +use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::CSSStyleDeclarationMethods; +use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; +use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; +use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, jsstring_to_str}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::AnimationFrameCallback; +use dom::element::Element; +use dom::globalscope::GlobalScope; +use dom::node::{Node, window_from_node}; +use dom::window::Window; use ipc_channel::ipc::IpcSender; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; use js::rust::wrappers::ObjectClassName; use msg::constellation_msg::PipelineId; +use script_thread::Documents; use std::ffi::CStr; use std::str; use style::properties::longhands::{margin_bottom, margin_left, margin_right, margin_top}; @@ -172,8 +172,7 @@ pub fn handle_get_layout( paddingLeft: String::from(computed_style.PaddingLeft()), width: width, height: height, - })) - .unwrap(); + })).unwrap(); } fn determine_auto_margins(window: &Window, node: &Node) -> AutoMargins { diff --git a/components/script/docs/JS-Servos-only-GC.md b/components/script/docs/JS-Servos-only-GC.md index 4f67bade28a2..f2502691afdc 100644 --- a/components/script/docs/JS-Servos-only-GC.md +++ b/components/script/docs/JS-Servos-only-GC.md @@ -31,7 +31,7 @@ the underlying low-level object. If the JavaScript garbage collector determines that a reflector is no longer reachable, it destroys the reflector and decrements the reference count on the underlying object. -[uaf]: https://cwe.mitre.org/data/definitions/416.html +[uaf]: http://cwe.mitre.org/data/definitions/416.html [refcounting]: https://en.wikipedia.org/wiki/Reference_counting [gEBI]: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById @@ -157,7 +157,7 @@ storing a `Node` struct within a `Document` struct. As in C++, the fields of `Node` are included in-line with the fields of `Document`, without any pointer indirection, and the auto-generated `trace` method will visit them as well. -[document-spec]: https://dom.spec.whatwg.org/#interface-document +[document-spec]: http://dom.spec.whatwg.org/#interface-document A `Document` also has an associated `Window`, but this is not an 'is-a' relationship. The `Document` just has a pointer to a `Window`, one of many @@ -168,7 +168,7 @@ garbage collector about. We do this with a above). The implementation of `trace` for `Dom` is not auto-generated; this is where we actually call the SpiderMonkey trace hooks: -[dom]: https://doc.servo.org/script/dom/bindings/root/struct.Dom.html +[dom]: http://doc.servo.org/script/dom/bindings/root/struct.Dom.html ```rust pub fn trace_reflector(tracer: *mut JSTracer, description: &str, reflector: &Reflector) { @@ -218,7 +218,7 @@ often called from JavaScript through [IDL-based bindings][bindings]. In this case, the bindings code constructs a [root][gc-root] for any involved DOM objects. -[bindings]: https://doc.servo.org/script/dom/bindings/index.html +[bindings]: http://doc.servo.org/script/dom/bindings/index.html [gc-root]: https://en.wikipedia.org/wiki/Tracing_garbage_collection#Reachability_of_an_object Another common situation is creating a stack-local root manually. For this @@ -232,10 +232,10 @@ In some cases, we need to use a DOM object longer than the reference we received allows us to; the [`DomRoot::from_ref` associated function][from-ref] allows creating a new `DomRoot` struct in that case. -[root]: https://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html +[root]: http://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html [raii]: https://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization -[new]: https://doc.servo.org/script/dom/index.html#construction -[from-ref]: https://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html#method.from_ref +[new]: http://doc.servo.org/script/dom/index.html#construction +[from-ref]: http://doc.servo.org/script/dom/bindings/root/struct.DomRoot.html#method.from_ref We can then obtain a reference from the `DomRoot` through Rust's built-in [`Deref` trait][deref], which exposes a method `deref` with the following @@ -285,7 +285,7 @@ use-after-free and other dangerous bugs. You can check out the [`root` module's documentation][root-docs] for more details that didn't make it into this document. -[root-docs]: https://doc.servo.org/script/dom/bindings/root/index.html +[root-docs]: http://doc.servo.org/script/dom/bindings/root/index.html Custom static analysis ====================== @@ -312,7 +312,7 @@ although in this case we set the default severity to 'error'. There is more information about lints in section 4.7 of the paper [Experience Report: Developing the Servo Web Browser Engine using Rust][lints]. -[lints]: https://arxiv.org/pdf/1505.07383v1.pdf +[lints]: http://arxiv.org/pdf/1505.07383v1.pdf We have already [implemented a plugin][js-lint] which effectively forbids `Dom` from appearing on the [stack][stack]. Because lint plugins are part of @@ -320,7 +320,7 @@ the usual [warnings infrastructure][warnings], we can use the `allow` attribute in places where it's okay to use `Dom`, like DOM struct definitions and the implementation of `Dom` itself. -[js-lint]: https://doc.servo.org/plugins/lints/unrooted_must_root/struct.UnrootedPass.html +[js-lint]: http://doc.servo.org/plugins/lints/unrooted_must_root/struct.UnrootedPass.html [stack]: https://en.wikipedia.org/wiki/Stack-based_memory_allocation [warnings]: https://doc.rust-lang.org/book/compiler-plugins.html#lint-plugins @@ -329,7 +329,7 @@ this adds only a fraction of a second to the compile time for Servo's largest subcomponent, as Rust compile times are dominated by [LLVM][llvm]'s back-end optimizations and code generation. -[llvm]: https://llvm.org/ +[llvm]: http://llvm.org/ In the end, the plugin won't necessarily catch every mistake. It's hard to achieve full [soundness][soundness] with ad-hoc extensions to a type system. @@ -351,8 +351,8 @@ a traditional reference-counted DOM. The [Blink][blink] team has also performed have Servo's luxury of starting from a clean slate and using a cutting-edge language. -[blink]: https://www.chromium.org/blink -[blink-gc]: https://www.chromium.org/blink/blink-gc +[blink]: http://www.chromium.org/blink +[blink-gc]: http://www.chromium.org/blink/blink-gc In the future, we will likely attempt to merge the allocations of DOM objects into the allocations of their JavaScript reflectors. This could produce diff --git a/components/script/document_loader.rs b/components/script/document_loader.rs index 433641961d42..7d522b5e9873 100644 --- a/components/script/document_loader.rs +++ b/components/script/document_loader.rs @@ -6,13 +6,13 @@ //! //! -use crate::dom::bindings::root::Dom; -use crate::dom::document::Document; -use crate::fetch::FetchCanceller; +use dom::bindings::root::Dom; +use dom::document::Document; +use fetch::FetchCanceller; use ipc_channel::ipc::IpcSender; -use net_traits::request::RequestInit; use net_traits::{CoreResourceMsg, FetchChannels, FetchResponseMsg}; -use net_traits::{IpcSend, ResourceThreads}; +use net_traits::{ResourceThreads, IpcSend}; +use net_traits::request::RequestInit; use servo_url::ServoUrl; use std::thread; @@ -153,8 +153,7 @@ impl DocumentLoader { .send(CoreResourceMsg::Fetch( request, FetchChannels::ResponseMsg(fetch_target, Some(cancel_receiver)), - )) - .unwrap(); + )).unwrap(); } /// Mark an in-progress network request complete. diff --git a/components/script/dom/abstractworker.rs b/components/script/dom/abstractworker.rs index 05b120a52843..2038ff62476e 100644 --- a/components/script/dom/abstractworker.rs +++ b/components/script/dom/abstractworker.rs @@ -2,10 +2,10 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::structuredclone::StructuredCloneData; -use crate::script_runtime::CommonScriptMsg; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::DomObject; +use dom::bindings::structuredclone::StructuredCloneData; +use script_runtime::CommonScriptMsg; /// Messages used to control the worker event loops pub enum WorkerScriptMsg { diff --git a/components/script/dom/abstractworkerglobalscope.rs b/components/script/dom/abstractworkerglobalscope.rs index e01b98cf944a..051469520ece 100644 --- a/components/script/dom/abstractworkerglobalscope.rs +++ b/components/script/dom/abstractworkerglobalscope.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::abstractworker::WorkerScriptMsg; -use crate::dom::bindings::conversions::DerivedFrom; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScriptMsg}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::worker::TrustedWorkerAddress; -use crate::dom::workerglobalscope::WorkerGlobalScope; -use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; -use crate::task_queue::{QueuedTaskConversion, TaskQueue}; use devtools_traits::DevtoolScriptControlMsg; +use dom::abstractworker::WorkerScriptMsg; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::reflector::DomObject; +use dom::dedicatedworkerglobalscope::{AutoWorkerReset, DedicatedWorkerScriptMsg}; +use dom::globalscope::GlobalScope; +use dom::worker::TrustedWorkerAddress; +use dom::workerglobalscope::WorkerGlobalScope; +use script_runtime::{ScriptChan, CommonScriptMsg, ScriptPort}; use servo_channel::{Receiver, Sender}; +use task_queue::{QueuedTaskConversion, TaskQueue}; /// A ScriptChan that can be cloned freely and will silently send a TrustedWorkerAddress with /// common event loop messages. While this SendableWorkerScriptChan is alive, the associated @@ -32,7 +32,7 @@ impl ScriptChan for SendableWorkerScriptChan { self.sender.send(msg).map_err(|_| ()) } - fn clone(&self) -> Box { + fn clone(&self) -> Box { Box::new(SendableWorkerScriptChan { sender: self.sender.clone(), worker: self.worker.clone(), @@ -58,7 +58,7 @@ impl ScriptChan for WorkerThreadWorkerChan { self.sender.send(msg).map_err(|_| ()) } - fn clone(&self) -> Box { + fn clone(&self) -> Box { Box::new(WorkerThreadWorkerChan { sender: self.sender.clone(), worker: self.worker.clone(), diff --git a/components/script/dom/activation.rs b/components/script/dom/activation.rs index c36151c2581a..9498f17bf178 100644 --- a/components/script/dom/activation.rs +++ b/components/script/dom/activation.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::str::DOMString; -use crate::dom::element::Element; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::window_from_node; -use crate::dom::window::ReflowReason; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::str::DOMString; +use dom::element::Element; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::EventTarget; +use dom::mouseevent::MouseEvent; +use dom::node::window_from_node; +use dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; /// Trait for elements with defined activation behavior diff --git a/components/script/dom/analysernode.rs b/components/script/dom/analysernode.rs index cf04bd44fcac..27f2f27b386d 100644 --- a/components/script/dom/analysernode.rs +++ b/components/script/dom/analysernode.rs @@ -2,22 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::AudioNode; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::{ - self, AnalyserNodeMethods, AnalyserOptions, -}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::window::Window; -use crate::task_source::{TaskSource, TaskSourceName}; +use dom::audionode::AudioNode; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AnalyserNodeBinding::{self, AnalyserNodeMethods, AnalyserOptions}; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::num::Finite; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::window::Window; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcReceiver}; use ipc_channel::router::ROUTER; @@ -26,6 +21,7 @@ use js::typedarray::{Float32Array, Uint8Array}; use servo_media::audio::analyser_node::AnalysisEngine; use servo_media::audio::block::Block; use servo_media::audio::node::AudioNodeInit; +use task_source::{TaskSource, TaskSourceName}; #[dom_struct] pub struct AnalyserNode { @@ -41,20 +37,17 @@ impl AnalyserNode { context: &BaseAudioContext, options: &AnalyserOptions, ) -> Fallible<(AnalyserNode, IpcReceiver)> { - let node_options = - options - .parent - .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); - - if options.fftSize > 32768 || - options.fftSize < 32 || - (options.fftSize & (options.fftSize - 1) != 0) - { - return Err(Error::IndexSize); + let node_options = options.parent + .unwrap_or(2, ChannelCountMode::Max, + ChannelInterpretation::Speakers); + + if options.fftSize > 32768 || options.fftSize < 32 || + (options.fftSize & (options.fftSize - 1) != 0) { + return Err(Error::IndexSize) } if *options.maxDecibels <= *options.minDecibels { - return Err(Error::IndexSize); + return Err(Error::IndexSize) } if *options.smoothingTimeConstant < 0. || *options.smoothingTimeConstant > 1. { @@ -74,19 +67,14 @@ impl AnalyserNode { 1, // outputs )?; - let engine = AnalysisEngine::new( - options.fftSize as usize, - *options.smoothingTimeConstant, - *options.minDecibels, - *options.maxDecibels, - ); - Ok(( - AnalyserNode { - node, - engine: DomRefCell::new(engine), - }, - rcv, - )) + + let engine = AnalysisEngine::new(options.fftSize as usize, + *options.smoothingTimeConstant, + *options.minDecibels, *options.maxDecibels); + Ok((AnalyserNode { + node, + engine: DomRefCell::new(engine) + }, rcv)) } #[allow(unrooted_must_root)] @@ -101,19 +89,13 @@ impl AnalyserNode { let canceller = window.task_canceller(TaskSourceName::DOMManipulation); let this = Trusted::new(&*object); - ROUTER.add_route( - recv.to_opaque(), - Box::new(move |block| { - let this = this.clone(); - let _ = source.queue_with_canceller( - task!(append_analysis_block: move || { + ROUTER.add_route(recv.to_opaque(), Box::new(move |block| { + let this = this.clone(); + let _ = source.queue_with_canceller(task!(append_analysis_block: move || { let this = this.root(); this.push_block(block.to().unwrap()) - }), - &canceller, - ); - }), - ); + }), &canceller); + })); Ok(object) } @@ -148,6 +130,7 @@ impl AnalyserNodeMethods for AnalyserNode { // run whilst we're writing to it let dest = unsafe { array.as_mut_slice() }; self.engine.borrow_mut().fill_byte_frequency_data(dest); + } #[allow(unsafe_code)] @@ -157,6 +140,7 @@ impl AnalyserNodeMethods for AnalyserNode { // run whilst we're writing to it let dest = unsafe { array.as_mut_slice() }; self.engine.borrow().fill_time_domain_data(dest); + } #[allow(unsafe_code)] @@ -166,12 +150,14 @@ impl AnalyserNodeMethods for AnalyserNode { // run whilst we're writing to it let dest = unsafe { array.as_mut_slice() }; self.engine.borrow().fill_byte_time_domain_data(dest); + } /// https://webaudio.github.io/web-audio-api/#dom-analysernode-fftsize fn SetFftSize(&self, value: u32) -> Fallible<()> { - if value > 32768 || value < 32 || (value & (value - 1) != 0) { - return Err(Error::IndexSize); + if value > 32768 || value < 32 || + (value & (value - 1) != 0) { + return Err(Error::IndexSize) } self.engine.borrow_mut().set_fft_size(value as usize); Ok(()) @@ -195,7 +181,7 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-mindecibels fn SetMinDecibels(&self, value: Finite) -> Fallible<()> { if *value >= self.engine.borrow().get_max_decibels() { - return Err(Error::IndexSize); + return Err(Error::IndexSize) } self.engine.borrow_mut().set_min_decibels(*value); Ok(()) @@ -209,7 +195,7 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-maxdecibels fn SetMaxDecibels(&self, value: Finite) -> Fallible<()> { if *value <= self.engine.borrow().get_min_decibels() { - return Err(Error::IndexSize); + return Err(Error::IndexSize) } self.engine.borrow_mut().set_max_decibels(*value); Ok(()) @@ -223,9 +209,10 @@ impl AnalyserNodeMethods for AnalyserNode { /// https://webaudio.github.io/web-audio-api/#dom-analysernode-smoothingtimeconstant fn SetSmoothingTimeConstant(&self, value: Finite) -> Fallible<()> { if *value < 0. || *value > 1. { - return Err(Error::IndexSize); + return Err(Error::IndexSize) } self.engine.borrow_mut().set_smoothing_constant(*value); Ok(()) } } + diff --git a/components/script/dom/attr.rs b/components/script/dom/attr.rs index 955b05ebdd95..e14dadec1a04 100644 --- a/components/script/dom/attr.rs +++ b/components/script/dom/attr.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::customelementregistry::CallbackReaction; -use crate::dom::element::{AttributeMutation, Element}; -use crate::dom::mutationobserver::{Mutation, MutationObserver}; -use crate::dom::node::Node; -use crate::dom::virtualmethods::vtable_for; -use crate::dom::window::Window; -use crate::script_thread::ScriptThread; use devtools_traits::AttrInfo; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AttrBinding::{self, AttrMethods}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{DomRoot, LayoutDom, MutNullableDom, RootedReference}; +use dom::bindings::str::DOMString; +use dom::customelementregistry::CallbackReaction; +use dom::element::{AttributeMutation, Element}; +use dom::mutationobserver::{Mutation, MutationObserver}; +use dom::node::Node; +use dom::virtualmethods::vtable_for; +use dom::window::Window; use dom_struct::dom_struct; -use html5ever::{LocalName, Namespace, Prefix}; +use html5ever::{Prefix, LocalName, Namespace}; +use script_thread::ScriptThread; use servo_atoms::Atom; use std::borrow::ToOwned; use std::cell::Ref; diff --git a/components/script/dom/audiobuffer.rs b/components/script/dom/audiobuffer.rs index 8aa05a35e112..a7b7467f14cc 100644 --- a/components/script/dom/audiobuffer.rs +++ b/components/script/dom/audiobuffer.rs @@ -2,58 +2,40 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::MAX_CHANNEL_COUNT; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AudioBufferBinding::{ - self, AudioBufferMethods, AudioBufferOptions, -}; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::window::Window; +use dom::audionode::MAX_CHANNEL_COUNT; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AudioBufferBinding::{self, AudioBufferMethods, AudioBufferOptions}; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::window::Window; use dom_struct::dom_struct; -use js::jsapi::JS_GetArrayBufferViewBuffer; use js::jsapi::{Heap, JSAutoCompartment, JSContext, JSObject}; -use js::rust::wrappers::JS_DetachArrayBuffer; +use js::jsapi::JS_GetArrayBufferViewBuffer; use js::rust::CustomAutoRooterGuard; +use js::rust::wrappers::JS_DetachArrayBuffer; use js::typedarray::{CreateWith, Float32Array}; use servo_media::audio::buffer_source_node::AudioBuffer as ServoMediaAudioBuffer; -use std::cell::Ref; use std::cmp::min; use std::ptr::{self, NonNull}; -// Spec mandates at least [8000, 96000], we use [8000, 192000] to match Firefox +// This range is defined by the spec. // https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbuffer pub const MIN_SAMPLE_RATE: f32 = 8000.; -pub const MAX_SAMPLE_RATE: f32 = 192000.; +pub const MAX_SAMPLE_RATE: f32 = 96000.; type JSAudioChannel = Heap<*mut JSObject>; -/// The AudioBuffer keeps its data either in js_channels -/// or in shared_channels if js_channels buffers are detached. -/// -/// js_channels buffers are (re)attached right before calling GetChannelData -/// and remain attached until its contents are needed by some other API -/// implementation. Follow https://webaudio.github.io/web-audio-api/#acquire-the-content -/// to know in which situations js_channels buffers must be detached. -/// #[dom_struct] pub struct AudioBuffer { reflector_: Reflector, - /// Float32Arrays returned by calls to GetChannelData. js_channels: DomRefCell>, - /// Aggregates the data from js_channels. - /// This is Some iff the buffers in js_channels are detached. #[ignore_malloc_size_of = "servo_media"] - shared_channels: DomRefCell>, - /// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-samplerate + shared_channels: DomRefCell, sample_rate: f32, - /// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-length length: u32, - /// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-duration duration: f64, - /// https://webaudio.github.io/web-audio-api/#dom-audiobuffer-numberofchannels number_of_channels: u32, } @@ -65,7 +47,10 @@ impl AudioBuffer { AudioBuffer { reflector_: Reflector::new(), js_channels: DomRefCell::new(vec), - shared_channels: DomRefCell::new(None), + shared_channels: DomRefCell::new(ServoMediaAudioBuffer::new( + number_of_channels as u8, + length as usize, + )), sample_rate, length, duration: length as f64 / sample_rate as f64, @@ -83,7 +68,7 @@ impl AudioBuffer { ) -> DomRoot { let buffer = AudioBuffer::new_inherited(number_of_channels, length, sample_rate); let buffer = reflect_dom_object(Box::new(buffer), global, AudioBufferBinding::Wrap); - buffer.set_initial_data(initial_data); + buffer.set_channels(initial_data); buffer } @@ -111,16 +96,18 @@ impl AudioBuffer { // Initialize the underlying channels data with initial data provided by // the user or silence otherwise. - fn set_initial_data(&self, initial_data: Option<&[Vec]>) { - let mut channels = - ServoMediaAudioBuffer::new(self.number_of_channels as u8, self.length as usize); + #[allow(unsafe_code)] + pub fn set_channels(&self, initial_data: Option<&[Vec]>) { for channel in 0..self.number_of_channels { - channels.buffers[channel as usize] = match initial_data { + (*self.shared_channels.borrow_mut()).buffers[channel as usize] = match initial_data { Some(data) => data[channel as usize].clone(), None => vec![0.; self.length as usize], }; } - *self.shared_channels.borrow_mut() = Some(channels); + } + + pub fn get_channels(&self) -> ServoMediaAudioBuffer { + self.shared_channels.borrow().clone() } #[allow(unsafe_code)] @@ -130,38 +117,35 @@ impl AudioBuffer { for (i, channel) in self.js_channels.borrow_mut().iter().enumerate() { if !channel.get().is_null() { // Already have data in JS array. + // We may have called GetChannelData, and web content may have modified + // js_channels. So make sure that shared_channels contains the same data as + // js_channels. + typedarray!(in(cx) let array: Float32Array = channel.get()); + if let Ok(array) = array { + (*self.shared_channels.borrow_mut()).buffers[i] = array.to_vec(); + } continue; } + // Copy the channel data from shared_channels to js_channels. rooted!(in (cx) let mut array = ptr::null_mut::()); - if let Some(ref shared_channels) = *self.shared_channels.borrow() { - // Step 4. of - // https://webaudio.github.io/web-audio-api/#acquire-the-content - // "Attach ArrayBuffers containing copies of the data to the AudioBuffer, - // to be returned by the next call to getChannelData()". - if Float32Array::create( - cx, - CreateWith::Slice(&shared_channels.buffers[i]), - array.handle_mut(), - ) - .is_err() - { - return false; - } + if Float32Array::create( + cx, + CreateWith::Slice(&(*self.shared_channels.borrow_mut()).buffers[i]), + array.handle_mut(), + ).is_err() + { + return false; } channel.set(array.get()); } - *self.shared_channels.borrow_mut() = None; - true } // https://webaudio.github.io/web-audio-api/#acquire-the-content #[allow(unsafe_code)] - fn acquire_contents(&self) -> Option { - let mut result = - ServoMediaAudioBuffer::new(self.number_of_channels as u8, self.length as usize); + pub fn acquire_contents(&self) -> Option { let cx = self.global().get_cx(); for (i, channel) in self.js_channels.borrow_mut().iter().enumerate() { // Step 1. @@ -189,20 +173,13 @@ impl AudioBuffer { channel.set(ptr::null_mut()); // Step 3. - result.buffers[i] = channel_data; - } - - Some(result) - } + (*self.shared_channels.borrow_mut()).buffers[i] = channel_data; - pub fn get_channels(&self) -> Ref> { - if self.shared_channels.borrow().is_none() { - let channels = self.acquire_contents(); - if channels.is_some() { - *self.shared_channels.borrow_mut() = channels; - } + // Step 4 will complete turning shared_channels + // data into js_channels ArrayBuffers in restore_js_channel_data. } - return self.shared_channels.borrow(); + + Some((*self.shared_channels.borrow()).clone()) } } @@ -277,10 +254,10 @@ impl AudioBufferMethods for AudioBuffer { let data = unsafe { array.as_slice() }; dest.extend_from_slice(&data[offset..offset + bytes_to_copy]); } - } else if let Some(ref shared_channels) = *self.shared_channels.borrow() { - if let Some(shared_channel) = shared_channels.buffers.get(channel_number) { - dest.extend_from_slice(&shared_channel.as_slice()[offset..offset + bytes_to_copy]); - } + } else if let Some(shared_channel) = + self.shared_channels.borrow().buffers.get(channel_number) + { + dest.extend_from_slice(&shared_channel.as_slice()[offset..offset + bytes_to_copy]); } unsafe { @@ -320,12 +297,21 @@ impl AudioBufferMethods for AudioBuffer { typedarray!(in(cx) let js_channel: Float32Array = js_channel); if let Ok(mut js_channel) = js_channel { let bytes_to_copy = min(self.length - start_in_channel, source.len() as u32) as usize; - let js_channel_data = unsafe { js_channel.as_mut_slice() }; - let (_, js_channel_data) = js_channel_data.split_at_mut(start_in_channel as usize); unsafe { - js_channel_data[0..bytes_to_copy] - .copy_from_slice(&source.as_slice()[0..bytes_to_copy]) - }; + let data = &source.as_slice()[0..bytes_to_copy]; + // Update shared channel. + { + let mut shared_channels = self.shared_channels.borrow_mut(); + let shared_channel = shared_channels.data_chan_mut(channel_number as u8); + let (_, mut shared_channel) = + shared_channel.split_at_mut(start_in_channel as usize); + shared_channel[0..bytes_to_copy].copy_from_slice(data); + } + // Update js channel. + js_channel.update( + self.shared_channels.borrow().buffers[channel_number as usize].as_slice(), + ); + } } else { return Err(Error::IndexSize); } diff --git a/components/script/dom/audiobuffersourcenode.rs b/components/script/dom/audiobuffersourcenode.rs index 09f6e7dadc6e..7a2817e12049 100644 --- a/components/script/dom/audiobuffersourcenode.rs +++ b/components/script/dom/audiobuffersourcenode.rs @@ -2,25 +2,25 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audiobuffer::AudioBuffer; -use crate::dom::audioparam::AudioParam; -use crate::dom::audioscheduledsourcenode::AudioScheduledSourceNode; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding; -use crate::dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceNodeMethods; -use crate::dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceOptions; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::codegen::Bindings::AudioScheduledSourceNodeBinding::AudioScheduledSourceNodeMethods; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::window::Window; +use dom::audiobuffer::AudioBuffer; +use dom::audioparam::AudioParam; +use dom::audioscheduledsourcenode::AudioScheduledSourceNode; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding; +use dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceNodeMethods; +use dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceOptions; +use dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; +use dom::bindings::codegen::Bindings::AudioScheduledSourceNodeBinding::AudioScheduledSourceNodeMethods; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::buffer_source_node::AudioBufferSourceNodeMessage; use servo_media::audio::buffer_source_node::AudioBufferSourceNodeOptions; -use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage}; +use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit}; use servo_media::audio::param::ParamType; use std::cell::Cell; use std::f32; @@ -137,14 +137,14 @@ impl AudioBufferSourceNodeMethods for AudioBufferSourceNode { self.buffer.set(new_buffer); // Step 5. - if self.source_node.has_start() { + if self.source_node.started() { if let Some(buffer) = self.buffer.get() { - let buffer = buffer.get_channels(); + let buffer = buffer.acquire_contents(); if buffer.is_some() { self.source_node .node() .message(AudioNodeMessage::AudioBufferSourceNode( - AudioBufferSourceNodeMessage::SetBuffer((*buffer).clone()), + AudioBufferSourceNodeMessage::SetBuffer(buffer), )); } } @@ -215,12 +215,12 @@ impl AudioBufferSourceNodeMethods for AudioBufferSourceNode { } if let Some(buffer) = self.buffer.get() { - let buffer = buffer.get_channels(); + let buffer = buffer.acquire_contents(); if buffer.is_some() { self.source_node .node() .message(AudioNodeMessage::AudioBufferSourceNode( - AudioBufferSourceNodeMessage::SetBuffer((*buffer).clone()), + AudioBufferSourceNodeMessage::SetBuffer(buffer), )); } } @@ -235,7 +235,7 @@ impl<'a> From<&'a AudioBufferSourceOptions> for AudioBufferSourceNodeOptions { Self { buffer: if let Some(ref buffer) = options.buffer { if let Some(ref buffer) = buffer { - (*buffer.get_channels()).clone() + Some(buffer.get_channels()) } else { None } diff --git a/components/script/dom/audiocontext.rs b/components/script/dom/audiocontext.rs index 03cdb5161390..eef971fcba5a 100644 --- a/components/script/dom/audiocontext.rs +++ b/components/script/dom/audiocontext.rs @@ -2,28 +2,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::baseaudiocontext::{BaseAudioContext, BaseAudioContextOptions}; -use crate::dom::bindings::codegen::Bindings::AudioContextBinding; -use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{ - AudioContextLatencyCategory, AudioContextMethods, -}; -use crate::dom::bindings::codegen::Bindings::AudioContextBinding::{ - AudioContextOptions, AudioTimestamp, -}; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextBinding::BaseAudioContextMethods; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::promise::Promise; -use crate::dom::window::Window; -use crate::task_source::TaskSource; +use dom::baseaudiocontext::{BaseAudioContext, BaseAudioContextOptions}; +use dom::bindings::codegen::Bindings::AudioContextBinding; +use dom::bindings::codegen::Bindings::AudioContextBinding::{AudioContextLatencyCategory, AudioContextMethods}; +use dom::bindings::codegen::Bindings::AudioContextBinding::{AudioContextOptions, AudioTimestamp}; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextBinding::BaseAudioContextMethods; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::refcounted::{Trusted, TrustedPromise}; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::promise::Promise; +use dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::context::{LatencyCategory, ProcessingState, RealTimeAudioContextOptions}; use std::rc::Rc; +use task_source::TaskSource; #[dom_struct] pub struct AudioContext { diff --git a/components/script/dom/audiodestinationnode.rs b/components/script/dom/audiodestinationnode.rs index 42336b862aaa..4c3949196714 100644 --- a/components/script/dom/audiodestinationnode.rs +++ b/components/script/dom/audiodestinationnode.rs @@ -2,18 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioDestinationNodeBinding::{ - self, AudioDestinationNodeMethods, -}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioDestinationNodeBinding::{self, AudioDestinationNodeMethods}; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[dom_struct] diff --git a/components/script/dom/audiolistener.rs b/components/script/dom/audiolistener.rs index f9ad0ff35d01..0287816f9213 100644 --- a/components/script/dom/audiolistener.rs +++ b/components/script/dom/audiolistener.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audioparam::AudioParam; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioListenerBinding::{self, AudioListenerMethods}; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::window::Window; +use dom::audioparam::AudioParam; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioListenerBinding::{self, AudioListenerMethods}; +use dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::window::Window; use dom_struct::dom_struct; -use servo_media::audio::param::{ParamDir, ParamType}; +use servo_media::audio::param::{ParamType, ParamDir}; use std::f32; #[dom_struct] diff --git a/components/script/dom/audionode.rs b/components/script/dom/audionode.rs index 17aabade2e78..e227f7282ffa 100644 --- a/components/script/dom/audionode.rs +++ b/components/script/dom/audionode.rs @@ -2,24 +2,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audioparam::AudioParam; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - AudioNodeMethods, AudioNodeOptions, -}; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::codegen::InheritTypes::{AudioNodeTypeId, EventTargetTypeId}; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::eventtarget::EventTarget; +use dom::audioparam::AudioParam; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{AudioNodeMethods, AudioNodeOptions}; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::InheritTypes::{AudioNodeTypeId, EventTargetTypeId}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{Dom, DomRoot}; +use dom::eventtarget::EventTarget; use dom_struct::dom_struct; use servo_media::audio::graph::NodeId; +use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit, ChannelInfo}; use servo_media::audio::node::ChannelCountMode as ServoMediaChannelCountMode; use servo_media::audio::node::ChannelInterpretation as ServoMediaChannelInterpretation; -use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage, ChannelInfo}; use std::cell::Cell; // 32 is the minimum required by the spec for createBuffer() and the deprecated diff --git a/components/script/dom/audioparam.rs b/components/script/dom/audioparam.rs index 659b4dde76dc..40826790cbfa 100644 --- a/components/script/dom/audioparam.rs +++ b/components/script/dom/audioparam.rs @@ -2,15 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::{ - AudioParamMethods, AutomationRate, -}; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::window::Window; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioParamBinding; +use dom::bindings::codegen::Bindings::AudioParamBinding::{AudioParamMethods, AutomationRate}; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::graph::NodeId; use servo_media::audio::node::AudioNodeMessage; diff --git a/components/script/dom/audioscheduledsourcenode.rs b/components/script/dom/audioscheduledsourcenode.rs index 31527fda3de5..6e15148993cc 100644 --- a/components/script/dom/audioscheduledsourcenode.rs +++ b/components/script/dom/audioscheduledsourcenode.rs @@ -1,26 +1,25 @@ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ - -use crate::dom::audionode::{AudioNode, UnwrappedAudioNodeOptions}; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioScheduledSourceNodeBinding::AudioScheduledSourceNodeMethods; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::DomObject; -use crate::task_source::{TaskSource, TaskSourceName}; +use dom::audionode::{AudioNode, UnwrappedAudioNodeOptions}; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioScheduledSourceNodeBinding::AudioScheduledSourceNodeMethods; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::DomObject; use dom_struct::dom_struct; +use servo_media::audio::node::{AudioNodeMessage, AudioNodeInit, AudioScheduledSourceNodeMessage}; use servo_media::audio::node::OnEndedCallback; -use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage, AudioScheduledSourceNodeMessage}; use std::cell::Cell; +use task_source::{TaskSource, TaskSourceName}; #[dom_struct] pub struct AudioScheduledSourceNode { node: AudioNode, - has_start: Cell, - has_stop: Cell, + started: Cell, + stopped: Cell, } impl AudioScheduledSourceNode { @@ -40,8 +39,8 @@ impl AudioScheduledSourceNode { number_of_inputs, number_of_outputs, )?, - has_start: Cell::new(false), - has_stop: Cell::new(false), + started: Cell::new(false), + stopped: Cell::new(false), }) } @@ -49,8 +48,8 @@ impl AudioScheduledSourceNode { &self.node } - pub fn has_start(&self) -> bool { - self.has_start.get() + pub fn started(&self) -> bool { + self.started.get() } } @@ -64,7 +63,7 @@ impl AudioScheduledSourceNodeMethods for AudioScheduledSourceNode { return Err(Error::Range("'when' must be a positive value".to_owned())); } - if self.has_start.get() || self.has_stop.get() { + if self.started.get() || self.stopped.get() { return Err(Error::InvalidState); } @@ -94,7 +93,7 @@ impl AudioScheduledSourceNodeMethods for AudioScheduledSourceNode { AudioScheduledSourceNodeMessage::RegisterOnEndedCallback(callback), )); - self.has_start.set(true); + self.started.set(true); self.node .message(AudioNodeMessage::AudioScheduledSourceNode( AudioScheduledSourceNodeMessage::Start(*when), @@ -108,10 +107,10 @@ impl AudioScheduledSourceNodeMethods for AudioScheduledSourceNode { return Err(Error::Range("'when' must be a positive value".to_owned())); } - if !self.has_start.get() { + if !self.started.get() { return Err(Error::InvalidState); } - self.has_stop.set(true); + self.stopped.set(true); self.node .message(AudioNodeMessage::AudioScheduledSourceNode( AudioScheduledSourceNodeMessage::Stop(*when), diff --git a/components/script/dom/baseaudiocontext.rs b/components/script/dom/baseaudiocontext.rs index 3b9a0a6b1057..b892049a8ec2 100644 --- a/components/script/dom/baseaudiocontext.rs +++ b/components/script/dom/baseaudiocontext.rs @@ -2,58 +2,56 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::analysernode::AnalyserNode; -use crate::dom::audiobuffer::AudioBuffer; -use crate::dom::audiobuffersourcenode::AudioBufferSourceNode; -use crate::dom::audiodestinationnode::AudioDestinationNode; -use crate::dom::audiolistener::AudioListener; -use crate::dom::audionode::MAX_CHANNEL_COUNT; -use crate::dom::bindings::callback::ExceptionHandling; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AnalyserNodeBinding::AnalyserOptions; -use crate::dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceOptions; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextMethods; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::DecodeErrorCallback; -use crate::dom::bindings::codegen::Bindings::BaseAudioContextBinding::DecodeSuccessCallback; -use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterOptions; -use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::ChannelMergerOptions; -use crate::dom::bindings::codegen::Bindings::GainNodeBinding::GainOptions; -use crate::dom::bindings::codegen::Bindings::OscillatorNodeBinding::OscillatorOptions; -use crate::dom::bindings::codegen::Bindings::PannerNodeBinding::PannerOptions; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::biquadfilternode::BiquadFilterNode; -use crate::dom::channelmergernode::ChannelMergerNode; -use crate::dom::domexception::{DOMErrorName, DOMException}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::gainnode::GainNode; -use crate::dom::oscillatornode::OscillatorNode; -use crate::dom::pannernode::PannerNode; -use crate::dom::promise::Promise; -use crate::dom::window::Window; -use crate::task_source::{TaskSource, TaskSourceName}; +use dom::analysernode::AnalyserNode; +use dom::audiobuffer::AudioBuffer; +use dom::audiobuffersourcenode::AudioBufferSourceNode; +use dom::audiodestinationnode::AudioDestinationNode; +use dom::audiolistener::AudioListener; +use dom::audionode::MAX_CHANNEL_COUNT; +use dom::bindings::callback::ExceptionHandling; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AnalyserNodeBinding::AnalyserOptions; +use dom::bindings::codegen::Bindings::AudioBufferSourceNodeBinding::AudioBufferSourceOptions; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::Bindings::AudioNodeBinding::AudioNodeOptions; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::AudioContextState; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::BaseAudioContextMethods; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::DecodeErrorCallback; +use dom::bindings::codegen::Bindings::BaseAudioContextBinding::DecodeSuccessCallback; +use dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterOptions; +use dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::ChannelMergerOptions; +use dom::bindings::codegen::Bindings::GainNodeBinding::GainOptions; +use dom::bindings::codegen::Bindings::OscillatorNodeBinding::OscillatorOptions; +use dom::bindings::codegen::Bindings::PannerNodeBinding::PannerOptions; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::biquadfilternode::BiquadFilterNode; +use dom::channelmergernode::ChannelMergerNode; +use dom::domexception::{DOMErrorName, DOMException}; +use dom::eventtarget::EventTarget; +use dom::gainnode::GainNode; +use dom::oscillatornode::OscillatorNode; +use dom::pannernode::PannerNode; +use dom::promise::Promise; +use dom::window::Window; use dom_struct::dom_struct; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBuffer; +use servo_media::{Backend, ServoMedia}; use servo_media::audio::context::{AudioContext, AudioContextOptions, ProcessingState}; use servo_media::audio::context::{OfflineAudioContextOptions, RealTimeAudioContextOptions}; use servo_media::audio::decoder::AudioDecoderCallbacks; use servo_media::audio::graph::NodeId; -use servo_media::{Backend, ServoMedia}; use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::mem; use std::rc::Rc; use std::sync::{Arc, Mutex}; +use task_source::{TaskSource, TaskSourceName}; use uuid::Uuid; #[allow(dead_code)] @@ -350,11 +348,7 @@ impl BaseAudioContextMethods for BaseAudioContext { /// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createbiquadfilter fn CreateBiquadFilter(&self) -> Fallible> { - BiquadFilterNode::new( - &self.global().as_window(), - &self, - &BiquadFilterOptions::empty(), - ) + BiquadFilterNode::new(&self.global().as_window(), &self, &BiquadFilterOptions::empty()) } /// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-createchannelmerger @@ -438,12 +432,10 @@ impl BaseAudioContextMethods for BaseAudioContext { .lock() .unwrap() .resize(channel_count as usize, Vec::new()); - }) - .progress(move |buffer, channel| { + }).progress(move |buffer, channel| { let mut decoded_audio = decoded_audio_.lock().unwrap(); decoded_audio[(channel - 1) as usize].extend_from_slice((*buffer).as_ref()); - }) - .eos(move || { + }).eos(move || { let _ = task_source.queue_with_canceller( task!(audio_decode_eos: move || { let this = this.root(); @@ -469,8 +461,7 @@ impl BaseAudioContextMethods for BaseAudioContext { }), &canceller, ); - }) - .error(move |error| { + }).error(move || { let _ = task_source_.queue_with_canceller( task!(audio_decode_eos: move || { let this = this_.root(); @@ -482,13 +473,11 @@ impl BaseAudioContextMethods for BaseAudioContext { &DOMException::new(&this.global(), DOMErrorName::DataCloneError), ExceptionHandling::Report); } - let error = format!("Audio decode error {:?}", error); - resolver.promise.reject_error(Error::Type(error)); + resolver.promise.reject_error(Error::Type("Audio decode error".to_owned())); }), &canceller_, ); - }) - .build(); + }).build(); self.audio_context_impl .decode_audio_data(audio_data, callbacks); } else { diff --git a/components/script/dom/beforeunloadevent.rs b/components/script/dom/beforeunloadevent.rs index a0422a7f7864..43f37a117e47 100644 --- a/components/script/dom/beforeunloadevent.rs +++ b/components/script/dom/beforeunloadevent.rs @@ -4,16 +4,16 @@ #![allow(dead_code)] -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding; -use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::window::Window; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding; +use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/bindings/callback.rs b/components/script/dom/bindings/callback.rs index 365817dcff19..ddc11ce25dad 100644 --- a/components/script/dom/bindings/callback.rs +++ b/components/script/dom/bindings/callback.rs @@ -4,19 +4,19 @@ //! Base classes to work with IDL callbacks. -use crate::dom::bindings::error::{report_pending_exception, Error, Fallible}; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}; -use crate::dom::bindings::utils::AsCCharPtrPtr; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::error::{Error, Fallible, report_pending_exception}; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::settings_stack::{AutoEntryScript, AutoIncumbentScript}; +use dom::bindings::utils::AsCCharPtrPtr; +use dom::globalscope::GlobalScope; +use js::jsapi::{IsCallable, JSContext, JSObject, AddRawValueRoot}; +use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment, RemoveRawValueRoot}; use js::jsapi::Heap; use js::jsapi::JSAutoCompartment; -use js::jsapi::{AddRawValueRoot, IsCallable, JSContext, JSObject}; -use js::jsapi::{JSCompartment, JS_EnterCompartment, JS_LeaveCompartment, RemoveRawValueRoot}; -use js::jsval::{JSVal, ObjectValue, UndefinedValue}; -use js::rust::wrappers::{JS_GetProperty, JS_WrapObject}; +use js::jsval::{JSVal, UndefinedValue, ObjectValue}; use js::rust::{MutableHandleObject, Runtime}; +use js::rust::wrappers::{JS_WrapObject, JS_GetProperty}; use std::default::Default; use std::ffi::CString; use std::mem::drop; diff --git a/components/script/dom/bindings/codegen/Bindings.conf b/components/script/dom/bindings/codegen/Bindings.conf index cdd41dc3b747..b97d199147b4 100644 --- a/components/script/dom/bindings/codegen/Bindings.conf +++ b/components/script/dom/bindings/codegen/Bindings.conf @@ -38,7 +38,7 @@ DOMInterfaces = { }, 'WindowProxy' : { - 'path': 'crate::dom::windowproxy::WindowProxy', + 'path': 'dom::windowproxy::WindowProxy', 'register': False, } diff --git a/components/script/dom/bindings/codegen/CodegenRust.py b/components/script/dom/bindings/codegen/CodegenRust.py index b50efc902071..39409e7deaa0 100644 --- a/components/script/dom/bindings/codegen/CodegenRust.py +++ b/components/script/dom/bindings/codegen/CodegenRust.py @@ -17,7 +17,6 @@ from WebIDL import ( BuiltinTypes, IDLBuiltinType, - IDLEmptySequenceValue, IDLInterfaceMember, IDLNullableType, IDLNullValue, @@ -674,19 +673,17 @@ def onFailureNotCallable(failureCode): ('throw_type_error(cx, \"%s is not callable.\");\n' '%s' % (firstCap(sourceDescription), exceptionCode))) - # A helper function for handling default values. - def handleDefault(nullValue): + # A helper function for handling null default values. Checks that the + # default value, if it exists, is null. + def handleDefaultNull(nullValue): if defaultValue is None: return None - if isinstance(defaultValue, IDLNullValue): - assert type.nullable() or type.isDictionary() - return nullValue - elif isinstance(defaultValue, IDLEmptySequenceValue): - assert type.isSequence() - return "Vec::new()" + if not isinstance(defaultValue, IDLNullValue): + raise TypeError("Can't handle non-null default value here") - raise TypeError("Can't handle non-null or non-empty sequence default value here") + assert type.nullable() or type.isDictionary() + return nullValue # A helper function for wrapping up the template body for # possibly-nullable objecty stuff @@ -729,7 +726,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, " _ => { %s },\n" "}" % (config, indent(failOrPropagate, 8), exceptionCode)) - return handleOptional(templateBody, declType, handleDefault("None")) + return handleOptional(templateBody, declType, handleDefaultNull("None")) if type.isUnion(): declType = CGGeneric(union_native_type(type)) @@ -761,7 +758,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, else: default = None else: - default = handleDefault("None") + default = handleDefaultNull("None") return handleOptional(templateBody, declType, default) @@ -813,7 +810,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, declType = CGGeneric("&Promise") else: declType = CGGeneric("Rc") - return handleOptional(templateBody, declType, handleDefault("None")) + return handleOptional(templateBody, declType, handleDefaultNull("None")) if type.isGeckoInterface(): assert not isEnforceRange and not isClamp @@ -831,7 +828,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, isDefinitelyObject, type, failureCode) - return handleOptional(template, declType, handleDefault("None")) + return handleOptional(template, declType, handleDefaultNull("None")) conversionFunction = "root_from_handlevalue" descriptorType = descriptor.returnType @@ -878,7 +875,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, templateBody = wrapObjectTemplate(templateBody, "None", isDefinitelyObject, type, failureCode) - return handleOptional(templateBody, declType, handleDefault("None")) + return handleOptional(templateBody, declType, handleDefaultNull("None")) if is_typed_array(type): if failureCode is None: @@ -921,7 +918,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, templateBody = wrapObjectTemplate(templateBody, "None", isDefinitelyObject, type, failureCode) - return handleOptional(templateBody, declType, handleDefault("None")) + return handleOptional(templateBody, declType, handleDefaultNull("None")) elif type.isSpiderMonkeyInterface(): raise TypeError("Can't handle SpiderMonkey interface arguments other than typed arrays yet") @@ -1148,7 +1145,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, isDefinitelyObject, type, failureCode) return handleOptional(templateBody, declType, - handleDefault(default)) + handleDefaultNull(default)) if type.isDictionary(): # There are no nullable dictionaries @@ -1170,7 +1167,7 @@ def wrapObjectTemplate(templateBody, nullValue, isDefinitelyObject, type, " _ => { %s },\n" "}" % (indent(failOrPropagate, 8), exceptionCode)) - return handleOptional(template, declType, handleDefault(empty)) + return handleOptional(template, declType, handleDefaultNull(empty)) if type.isVoid(): # This one only happens for return values, and its easy: Just @@ -2034,9 +2031,9 @@ def removeWrapperAndNullableTypes(types): descriptor = descriptorProvider.getDescriptor(parentName) extras += [descriptor.path, descriptor.bindingPath] elif t.isType() and t.isRecord(): - extras += ['crate::dom::bindings::mozmap::MozMap'] + extras += ['dom::bindings::mozmap::MozMap'] elif isinstance(t, IDLPromiseType): - extras += ['crate::dom::promise::Promise'] + extras += ["dom::promise::Promise"] else: if t.isEnum(): extras += [getModuleFromObject(t) + '::' + getIdentifier(t).name + 'Values'] @@ -2086,15 +2083,15 @@ def DOMClassTypeId(desc): inner = "" if desc.hasDescendants(): if desc.interface.getExtendedAttribute("Abstract"): - return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { abstract_: () }" + return "::dom::bindings::codegen::InheritTypes::TopTypeId { abstract_: () }" name = desc.interface.identifier.name - inner = "(crate::dom::bindings::codegen::InheritTypes::%sTypeId::%s)" % (name, name) + inner = "(::dom::bindings::codegen::InheritTypes::%sTypeId::%s)" % (name, name) elif len(protochain) == 1: - return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { alone: () }" + return "::dom::bindings::codegen::InheritTypes::TopTypeId { alone: () }" reversed_protochain = list(reversed(protochain)) for (child, parent) in zip(reversed_protochain, reversed_protochain[1:]): - inner = "(crate::dom::bindings::codegen::InheritTypes::%sTypeId::%s%s)" % (parent, child, inner) - return "crate::dom::bindings::codegen::InheritTypes::TopTypeId { %s: %s }" % (protochain[0].lower(), inner) + inner = "(::dom::bindings::codegen::InheritTypes::%sTypeId::%s%s)" % (parent, child, inner) + return "::dom::bindings::codegen::InheritTypes::TopTypeId { %s: %s }" % (protochain[0].lower(), inner) def DOMClass(descriptor): @@ -2130,7 +2127,7 @@ def __init__(self, descriptor): def define(self): parentName = self.descriptor.getParentName() if not parentName: - parentName = "crate::dom::bindings::reflector::Reflector" + parentName = "::dom::bindings::reflector::Reflector" args = { "domClass": DOMClass(self.descriptor), @@ -2194,7 +2191,7 @@ def define(self): if parent: parentName = parent.identifier.name else: - parentName = "crate::dom::bindings::reflector::Reflector" + parentName = "::dom::bindings::reflector::Reflector" selfName = self.descriptor.interface.identifier.name @@ -2205,7 +2202,7 @@ def define(self): # also has a reflector # # FIXME *RenderingContext2D should use Inline - parentName = "crate::dom::canvasrenderingcontext2d::CanvasRenderingContext2D" + parentName = "::dom::canvasrenderingcontext2d::CanvasRenderingContext2D" args = { "parentName": parentName, "selfName": selfName, @@ -2214,7 +2211,7 @@ def define(self): return """\ impl %(selfName)s { fn __assert_parent_type(&self) { - use crate::dom::bindings::inheritance::HasParent; + use dom::bindings::inheritance::HasParent; // If this type assertion fails, make sure the first field of your // DOM struct is of the correct type -- it must be the parent class. let _: &%(parentName)s = self.as_parent(); @@ -2281,14 +2278,7 @@ def define(self): return """\ static INTERFACE_OBJECT_CLASS: NonCallbackInterfaceObjectClass = NonCallbackInterfaceObjectClass::new( - { - // Intermediate `const` because as of nightly-2018-10-05, - // rustc is conservative in promotion to `'static` of the return values of `const fn`s: - // https://github.com/rust-lang/rust/issues/54846 - // https://github.com/rust-lang/rust/pull/53851 - const BEHAVIOR: InterfaceConstructorBehavior = %(constructorBehavior)s; - &BEHAVIOR - }, + &%(constructorBehavior)s, %(representation)s, PrototypeList::ID::%(id)s, %(depth)s); @@ -2374,22 +2364,22 @@ def UnionTypes(descriptors, dictionaries, callbacks, typedefs, config): """ imports = [ - 'crate::dom', - 'crate::dom::bindings::codegen::PrototypeList', - 'crate::dom::bindings::conversions::ConversionResult', - 'crate::dom::bindings::conversions::FromJSValConvertible', - 'crate::dom::bindings::conversions::ToJSValConvertible', - 'crate::dom::bindings::conversions::ConversionBehavior', - 'crate::dom::bindings::conversions::StringificationBehavior', - 'crate::dom::bindings::conversions::root_from_handlevalue', + 'dom', + 'dom::bindings::codegen::PrototypeList', + 'dom::bindings::conversions::ConversionResult', + 'dom::bindings::conversions::FromJSValConvertible', + 'dom::bindings::conversions::ToJSValConvertible', + 'dom::bindings::conversions::ConversionBehavior', + 'dom::bindings::conversions::StringificationBehavior', + 'dom::bindings::conversions::root_from_handlevalue', 'std::ptr::NonNull', - 'crate::dom::bindings::mozmap::MozMap', - 'crate::dom::bindings::root::DomRoot', - 'crate::dom::bindings::str::ByteString', - 'crate::dom::bindings::str::DOMString', - 'crate::dom::bindings::str::USVString', - 'crate::dom::bindings::trace::RootedTraceableBox', - 'crate::dom::types::*', + 'dom::bindings::mozmap::MozMap', + 'dom::bindings::root::DomRoot', + 'dom::bindings::str::ByteString', + 'dom::bindings::str::DOMString', + 'dom::bindings::str::USVString', + 'dom::bindings::trace::RootedTraceableBox', + 'dom::types::*', 'js::error::throw_type_error', 'js::rust::HandleValue', 'js::jsapi::Heap', @@ -4150,7 +4140,7 @@ def __init__(self, enum): pairs = ",\n ".join(['("%s", super::%s::%s)' % (val, ident, getEnumValueName(val)) for val in enum.values()]) inner = string.Template("""\ -use crate::dom::bindings::conversions::ToJSValConvertible; +use dom::bindings::conversions::ToJSValConvertible; use js::jsapi::JSContext; use js::rust::MutableHandleValue; use js::jsval::JSVal; @@ -5686,11 +5676,7 @@ def members(): yield name, arguments, rettype def fmt(arguments): - keywords = {"async"} - return "".join( - ", %s: %s" % (name if name not in keywords else "r#" + name, type_) - for name, type_ in arguments - ) + return "".join(", %s: %s" % argument for argument in arguments) def contains_unsafe_arg(arguments): if not arguments or len(arguments) == 0: @@ -5870,112 +5856,112 @@ def generate_imports(config, cgthings, descriptors, callbacks=None, dictionaries 'js::rust::define_properties', 'js::rust::get_object_class', 'js::typedarray', - 'crate::dom', - 'crate::dom::bindings', - 'crate::dom::bindings::codegen::InterfaceObjectMap', - 'crate::dom::bindings::constant::ConstantSpec', - 'crate::dom::bindings::constant::ConstantVal', - 'crate::dom::bindings::interface::ConstructorClassHook', - 'crate::dom::bindings::interface::InterfaceConstructorBehavior', - 'crate::dom::bindings::interface::NonCallbackInterfaceObjectClass', - 'crate::dom::bindings::interface::create_global_object', - 'crate::dom::bindings::interface::create_callback_interface_object', - 'crate::dom::bindings::interface::create_interface_prototype_object', - 'crate::dom::bindings::interface::create_named_constructors', - 'crate::dom::bindings::interface::create_noncallback_interface_object', - 'crate::dom::bindings::interface::define_guarded_constants', - 'crate::dom::bindings::interface::define_guarded_methods', - 'crate::dom::bindings::interface::define_guarded_properties', - 'crate::dom::bindings::htmlconstructor::html_constructor', - 'crate::dom::bindings::interface::is_exposed_in', - 'crate::dom::bindings::htmlconstructor::pop_current_element_queue', - 'crate::dom::bindings::htmlconstructor::push_new_element_queue', - 'crate::dom::bindings::iterable::Iterable', - 'crate::dom::bindings::iterable::IteratorType', - 'crate::dom::bindings::namespace::NamespaceObjectClass', - 'crate::dom::bindings::namespace::create_namespace_object', - 'crate::dom::bindings::reflector::MutDomObject', - 'crate::dom::bindings::reflector::DomObject', - 'crate::dom::bindings::root::Dom', - 'crate::dom::bindings::root::DomRoot', - 'crate::dom::bindings::root::OptionalHeapSetter', - 'crate::dom::bindings::root::RootedReference', - 'crate::dom::bindings::utils::AsVoidPtr', - 'crate::dom::bindings::utils::DOMClass', - 'crate::dom::bindings::utils::DOMJSClass', - 'crate::dom::bindings::utils::DOM_PROTO_UNFORGEABLE_HOLDER_SLOT', - 'crate::dom::bindings::utils::JSCLASS_DOM_GLOBAL', - 'crate::dom::bindings::utils::ProtoOrIfaceArray', - 'crate::dom::bindings::utils::enumerate_global', - 'crate::dom::bindings::utils::finalize_global', - 'crate::dom::bindings::utils::find_enum_value', - 'crate::dom::bindings::utils::generic_getter', - 'crate::dom::bindings::utils::generic_lenient_getter', - 'crate::dom::bindings::utils::generic_lenient_setter', - 'crate::dom::bindings::utils::generic_method', - 'crate::dom::bindings::utils::generic_setter', - 'crate::dom::bindings::utils::get_array_index_from_id', - 'crate::dom::bindings::utils::get_dictionary_property', - 'crate::dom::bindings::utils::get_property_on_prototype', - 'crate::dom::bindings::utils::get_proto_or_iface_array', - 'crate::dom::bindings::utils::has_property_on_prototype', - 'crate::dom::bindings::utils::is_platform_object', - 'crate::dom::bindings::utils::resolve_global', - 'crate::dom::bindings::utils::set_dictionary_property', - 'crate::dom::bindings::utils::trace_global', - 'crate::dom::bindings::trace::JSTraceable', - 'crate::dom::bindings::trace::RootedTraceable', - 'crate::dom::bindings::trace::RootedTraceableBox', - 'crate::dom::bindings::callback::CallSetup', - 'crate::dom::bindings::callback::CallbackContainer', - 'crate::dom::bindings::callback::CallbackInterface', - 'crate::dom::bindings::callback::CallbackFunction', - 'crate::dom::bindings::callback::CallbackObject', - 'crate::dom::bindings::callback::ExceptionHandling', - 'crate::dom::bindings::callback::wrap_call_this_object', - 'crate::dom::bindings::conversions::ConversionBehavior', - 'crate::dom::bindings::conversions::ConversionResult', - 'crate::dom::bindings::conversions::DOM_OBJECT_SLOT', - 'crate::dom::bindings::conversions::FromJSValConvertible', - 'crate::dom::bindings::conversions::IDLInterface', - 'crate::dom::bindings::conversions::StringificationBehavior', - 'crate::dom::bindings::conversions::ToJSValConvertible', - 'crate::dom::bindings::conversions::is_array_like', - 'crate::dom::bindings::conversions::native_from_handlevalue', - 'crate::dom::bindings::conversions::native_from_object', - 'crate::dom::bindings::conversions::private_from_object', - 'crate::dom::bindings::conversions::root_from_handleobject', - 'crate::dom::bindings::conversions::root_from_handlevalue', - 'crate::dom::bindings::conversions::root_from_object', - 'crate::dom::bindings::conversions::jsid_to_string', - 'crate::dom::bindings::codegen::PrototypeList', - 'crate::dom::bindings::codegen::RegisterBindings', - 'crate::dom::bindings::codegen::UnionTypes', - 'crate::dom::bindings::error::Error', - 'crate::dom::bindings::error::ErrorResult', - 'crate::dom::bindings::error::Fallible', - 'crate::dom::bindings::error::Error::JSFailed', - 'crate::dom::bindings::error::throw_dom_exception', - 'crate::dom::bindings::guard::Condition', - 'crate::dom::bindings::guard::Guard', - 'crate::dom::bindings::inheritance::Castable', - 'crate::dom::bindings::proxyhandler', - 'crate::dom::bindings::proxyhandler::ensure_expando_object', - 'crate::dom::bindings::proxyhandler::fill_property_descriptor', - 'crate::dom::bindings::proxyhandler::get_expando_object', - 'crate::dom::bindings::proxyhandler::get_property_descriptor', - 'crate::dom::bindings::mozmap::MozMap', + 'dom', + 'dom::bindings', + 'dom::bindings::codegen::InterfaceObjectMap', + 'dom::bindings::constant::ConstantSpec', + 'dom::bindings::constant::ConstantVal', + 'dom::bindings::interface::ConstructorClassHook', + 'dom::bindings::interface::InterfaceConstructorBehavior', + 'dom::bindings::interface::NonCallbackInterfaceObjectClass', + 'dom::bindings::interface::create_global_object', + 'dom::bindings::interface::create_callback_interface_object', + 'dom::bindings::interface::create_interface_prototype_object', + 'dom::bindings::interface::create_named_constructors', + 'dom::bindings::interface::create_noncallback_interface_object', + 'dom::bindings::interface::define_guarded_constants', + 'dom::bindings::interface::define_guarded_methods', + 'dom::bindings::interface::define_guarded_properties', + 'dom::bindings::htmlconstructor::html_constructor', + 'dom::bindings::interface::is_exposed_in', + 'dom::bindings::htmlconstructor::pop_current_element_queue', + 'dom::bindings::htmlconstructor::push_new_element_queue', + 'dom::bindings::iterable::Iterable', + 'dom::bindings::iterable::IteratorType', + 'dom::bindings::namespace::NamespaceObjectClass', + 'dom::bindings::namespace::create_namespace_object', + 'dom::bindings::reflector::MutDomObject', + 'dom::bindings::reflector::DomObject', + 'dom::bindings::root::Dom', + 'dom::bindings::root::DomRoot', + 'dom::bindings::root::OptionalHeapSetter', + 'dom::bindings::root::RootedReference', + 'dom::bindings::utils::AsVoidPtr', + 'dom::bindings::utils::DOMClass', + 'dom::bindings::utils::DOMJSClass', + 'dom::bindings::utils::DOM_PROTO_UNFORGEABLE_HOLDER_SLOT', + 'dom::bindings::utils::JSCLASS_DOM_GLOBAL', + 'dom::bindings::utils::ProtoOrIfaceArray', + 'dom::bindings::utils::enumerate_global', + 'dom::bindings::utils::finalize_global', + 'dom::bindings::utils::find_enum_value', + 'dom::bindings::utils::generic_getter', + 'dom::bindings::utils::generic_lenient_getter', + 'dom::bindings::utils::generic_lenient_setter', + 'dom::bindings::utils::generic_method', + 'dom::bindings::utils::generic_setter', + 'dom::bindings::utils::get_array_index_from_id', + 'dom::bindings::utils::get_dictionary_property', + 'dom::bindings::utils::get_property_on_prototype', + 'dom::bindings::utils::get_proto_or_iface_array', + 'dom::bindings::utils::has_property_on_prototype', + 'dom::bindings::utils::is_platform_object', + 'dom::bindings::utils::resolve_global', + 'dom::bindings::utils::set_dictionary_property', + 'dom::bindings::utils::trace_global', + 'dom::bindings::trace::JSTraceable', + 'dom::bindings::trace::RootedTraceable', + 'dom::bindings::trace::RootedTraceableBox', + 'dom::bindings::callback::CallSetup', + 'dom::bindings::callback::CallbackContainer', + 'dom::bindings::callback::CallbackInterface', + 'dom::bindings::callback::CallbackFunction', + 'dom::bindings::callback::CallbackObject', + 'dom::bindings::callback::ExceptionHandling', + 'dom::bindings::callback::wrap_call_this_object', + 'dom::bindings::conversions::ConversionBehavior', + 'dom::bindings::conversions::ConversionResult', + 'dom::bindings::conversions::DOM_OBJECT_SLOT', + 'dom::bindings::conversions::FromJSValConvertible', + 'dom::bindings::conversions::IDLInterface', + 'dom::bindings::conversions::StringificationBehavior', + 'dom::bindings::conversions::ToJSValConvertible', + 'dom::bindings::conversions::is_array_like', + 'dom::bindings::conversions::native_from_handlevalue', + 'dom::bindings::conversions::native_from_object', + 'dom::bindings::conversions::private_from_object', + 'dom::bindings::conversions::root_from_handleobject', + 'dom::bindings::conversions::root_from_handlevalue', + 'dom::bindings::conversions::root_from_object', + 'dom::bindings::conversions::jsid_to_string', + 'dom::bindings::codegen::PrototypeList', + 'dom::bindings::codegen::RegisterBindings', + 'dom::bindings::codegen::UnionTypes', + 'dom::bindings::error::Error', + 'dom::bindings::error::ErrorResult', + 'dom::bindings::error::Fallible', + 'dom::bindings::error::Error::JSFailed', + 'dom::bindings::error::throw_dom_exception', + 'dom::bindings::guard::Condition', + 'dom::bindings::guard::Guard', + 'dom::bindings::inheritance::Castable', + 'dom::bindings::proxyhandler', + 'dom::bindings::proxyhandler::ensure_expando_object', + 'dom::bindings::proxyhandler::fill_property_descriptor', + 'dom::bindings::proxyhandler::get_expando_object', + 'dom::bindings::proxyhandler::get_property_descriptor', + 'dom::bindings::mozmap::MozMap', 'std::ptr::NonNull', - 'crate::dom::bindings::num::Finite', - 'crate::dom::bindings::str::ByteString', - 'crate::dom::bindings::str::DOMString', - 'crate::dom::bindings::str::USVString', - 'crate::dom::bindings::weakref::DOM_WEAK_SLOT', - 'crate::dom::bindings::weakref::WeakBox', - 'crate::dom::bindings::weakref::WeakReferenceable', - 'crate::dom::windowproxy::WindowProxy', - 'crate::dom::globalscope::GlobalScope', - 'crate::mem::malloc_size_of_including_raw_self', + 'dom::bindings::num::Finite', + 'dom::bindings::str::ByteString', + 'dom::bindings::str::DOMString', + 'dom::bindings::str::USVString', + 'dom::bindings::weakref::DOM_WEAK_SLOT', + 'dom::bindings::weakref::WeakBox', + 'dom::bindings::weakref::WeakReferenceable', + 'dom::windowproxy::WindowProxy', + 'dom::globalscope::GlobalScope', + 'mem::malloc_size_of_including_raw_self', 'libc', 'servo_config::prefs::PREFS', 'std::borrow::ToOwned', @@ -6214,7 +6200,7 @@ def __init__(self, dictionary, descriptorProvider): descriptorProvider, isMember="Dictionary", defaultValue=member.defaultValue, - exceptionCode="return Err(());\n")) + exceptionCode="return Err(());")) for member in dictionary.members] def define(self): @@ -6254,7 +6240,7 @@ def impl(self): d = self.dictionary if d.parent: initParent = ("{\n" - " match r#try!(%s::%s::new(cx, val)) {\n" + " match try!(%s::%s::new(cx, val)) {\n" " ConversionResult::Success(v) => v,\n" " ConversionResult::Failure(error) => {\n" " throw_type_error(cx, &error);\n" @@ -6400,7 +6386,7 @@ def indent(s): conversion = ( "{\n" " rooted!(in(cx) let mut rval = UndefinedValue());\n" - " match r#try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" + " match try!(get_dictionary_property(cx, object.handle(), \"%s\", rval.handle_mut())) {\n" " true => {\n" "%s\n" " },\n" @@ -7171,7 +7157,7 @@ def getCallableDecl(self): "methodName": self.methodName } getCallableFromProp = string.Template( - 'r#try!(self.parent.get_callable_property(cx, "${methodName}"))' + 'try!(self.parent.get_callable_property(cx, "${methodName}"))' ).substitute(replacements) if not self.singleOperation: return 'rooted!(in(cx) let callable =\n' + getCallableFromProp + ');\n' @@ -7273,7 +7259,7 @@ class GlobalGenRoots(): @staticmethod def InterfaceObjectMap(config): mods = [ - "crate::dom::bindings::codegen", + "dom::bindings::codegen", "js::jsapi::JSContext", "js::rust::HandleObject", "phf", @@ -7355,8 +7341,8 @@ def RegisterBindings(config): ], "\n") return CGImports(code, descriptors=[], callbacks=[], dictionaries=[], enums=[], typedefs=[], imports=[ - 'crate::dom::bindings::codegen::Bindings', - 'crate::dom::bindings::codegen::PrototypeList::Proxies', + 'dom::bindings::codegen::Bindings', + 'dom::bindings::codegen::PrototypeList::Proxies', 'libc', ], config=config, ignored_warnings=[]) @@ -7366,8 +7352,8 @@ def InterfaceTypes(config): for d in config.getDescriptors(register=True, isCallback=False, isIteratorInterface=False)]) - curr = CGList([CGGeneric("pub use crate::dom::%s::%s;\n" % (name.lower(), - MakeNativeName(name))) + curr = CGList([CGGeneric("pub use dom::%s::%s;\n" % (name.lower(), + MakeNativeName(name))) for name in descriptors]) curr = CGWrapper(curr, pre=AUTOGENERATED_WARNING_COMMENT) return curr @@ -7390,12 +7376,12 @@ def leafModule(d): def InheritTypes(config): descriptors = config.getDescriptors(register=True, isCallback=False) - imports = [CGGeneric("use crate::dom::types::*;\n"), - CGGeneric("use crate::dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), - CGGeneric("use crate::dom::bindings::inheritance::Castable;\n"), - CGGeneric("use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"), - CGGeneric("use crate::dom::bindings::trace::JSTraceable;\n"), - CGGeneric("use crate::dom::bindings::reflector::DomObject;\n"), + imports = [CGGeneric("use dom::types::*;\n"), + CGGeneric("use dom::bindings::conversions::{DerivedFrom, get_dom_class};\n"), + CGGeneric("use dom::bindings::inheritance::Castable;\n"), + CGGeneric("use dom::bindings::root::{Dom, DomRoot, LayoutDom};\n"), + CGGeneric("use dom::bindings::trace::JSTraceable;\n"), + CGGeneric("use dom::bindings::reflector::DomObject;\n"), CGGeneric("use js::jsapi::JSTracer;\n\n"), CGGeneric("use std::mem;\n\n")] allprotos = [] diff --git a/components/script/dom/bindings/codegen/Configuration.py b/components/script/dom/bindings/codegen/Configuration.py index 92e0705d32be..4f56c4b55c33 100644 --- a/components/script/dom/bindings/codegen/Configuration.py +++ b/components/script/dom/bindings/codegen/Configuration.py @@ -204,9 +204,9 @@ def __init__(self, config, interface, desc): self.returnType = 'Rc<%s>' % typeName self.argumentType = '&%s' % typeName self.nativeType = typeName - pathDefault = 'crate::dom::types::%s' % typeName + pathDefault = 'dom::types::%s' % typeName elif self.interface.isCallback(): - ty = 'crate::dom::bindings::codegen::Bindings::%sBinding::%s' % (ifaceName, ifaceName) + ty = 'dom::bindings::codegen::Bindings::%sBinding::%s' % (ifaceName, ifaceName) pathDefault = ty self.returnType = "Rc<%s>" % ty self.argumentType = "???" @@ -216,14 +216,14 @@ def __init__(self, config, interface, desc): self.argumentType = "&%s" % typeName self.nativeType = "*const %s" % typeName if self.interface.isIteratorInterface(): - pathDefault = 'crate::dom::bindings::iterable::IterableIterator' + pathDefault = 'dom::bindings::iterable::IterableIterator' else: - pathDefault = 'crate::dom::types::%s' % MakeNativeName(typeName) + pathDefault = 'dom::types::%s' % MakeNativeName(typeName) self.concreteType = typeName self.register = desc.get('register', True) self.path = desc.get('path', pathDefault) - self.bindingPath = 'crate::dom::bindings::codegen::Bindings::%s' % ('::'.join([ifaceName + 'Binding'] * 2)) + self.bindingPath = 'dom::bindings::codegen::Bindings::%s' % ('::'.join([ifaceName + 'Binding'] * 2)) self.outerObjectHook = desc.get('outerObjectHook', 'None') self.proxy = False self.weakReferenceable = desc.get('weakReferenceable', False) @@ -422,7 +422,7 @@ def MakeNativeName(name): def getModuleFromObject(object): - return ('crate::dom::bindings::codegen::Bindings::' + + return ('dom::bindings::codegen::Bindings::' + os.path.basename(object.location.filename()).split('.webidl')[0] + 'Binding') diff --git a/components/script/dom/bindings/constant.rs b/components/script/dom/bindings/constant.rs index 56f5356c916c..0329d106132c 100644 --- a/components/script/dom/bindings/constant.rs +++ b/components/script/dom/bindings/constant.rs @@ -4,11 +4,12 @@ //! WebIDL constants. -use js::jsapi::JSPROP_READONLY; use js::jsapi::{JSContext, JSPROP_ENUMERATE, JSPROP_PERMANENT}; +use js::jsapi::JSPROP_READONLY; use js::jsval::{BooleanValue, DoubleValue, Int32Value, JSVal, NullValue, UInt32Value}; -use js::rust::wrappers::JS_DefineProperty; use js::rust::HandleObject; +use js::rust::wrappers::JS_DefineProperty; +use libc; /// Representation of an IDL constant. #[derive(Clone)] diff --git a/components/script/dom/bindings/conversions.rs b/components/script/dom/bindings/conversions.rs index cf3e45dd770a..4f848ea97d75 100644 --- a/components/script/dom/bindings/conversions.rs +++ b/components/script/dom/bindings/conversions.rs @@ -32,32 +32,32 @@ //! | sequences | `Vec` | | //! | union types | `T` | | -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::{ByteString, DOMString, USVString}; -use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; -use crate::dom::bindings::utils::DOMClass; -use js::conversions::latin1_to_string; -pub use js::conversions::ConversionBehavior; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{DomObject, Reflector}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::{ByteString, DOMString, USVString}; +use dom::bindings::trace::{JSTraceable, RootedTraceableBox}; +use dom::bindings::utils::DOMClass; +use js; pub use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; +pub use js::conversions::ConversionBehavior; +use js::conversions::latin1_to_string; use js::error::throw_type_error; -use js::glue::GetProxyReservedSlot; -use js::glue::JS_GetReservedSlot; use js::glue::{IsWrapper, UnwrapObject}; use js::glue::{RUST_JSID_IS_INT, RUST_JSID_TO_INT}; use js::glue::{RUST_JSID_IS_STRING, RUST_JSID_TO_STRING}; +use js::glue::GetProxyReservedSlot; +use js::glue::JS_GetReservedSlot; use js::jsapi::{Heap, JSContext, JSObject, JSString}; -use js::jsapi::{ - JS_GetLatin1StringCharsAndLength, JS_GetTwoByteStringCharsAndLength, JS_IsExceptionPending, -}; +use js::jsapi::{JS_GetLatin1StringCharsAndLength, JS_GetTwoByteStringCharsAndLength, JS_IsExceptionPending}; use js::jsapi::{JS_NewStringCopyN, JS_StringHasLatin1Chars}; use js::jsval::{ObjectValue, StringValue, UndefinedValue}; -use js::rust::wrappers::{JS_GetProperty, JS_IsArrayObject}; -use js::rust::{get_object_class, is_dom_class, is_dom_object, maybe_wrap_value, ToString}; use js::rust::{HandleId, HandleObject, HandleValue, MutableHandleValue}; +use js::rust::{get_object_class, is_dom_class, is_dom_object, maybe_wrap_value, ToString}; +use js::rust::wrappers::{JS_GetProperty, JS_IsArrayObject}; +use libc; use num_traits::Float; use servo_config::opts; use std::{char, ffi, ptr, slice}; @@ -65,7 +65,7 @@ use std::{char, ffi, ptr, slice}; /// A trait to check whether a given `JSObject` implements an IDL interface. pub trait IDLInterface { /// Returns whether the given DOM class derives that interface. - fn derives(_: &'static DOMClass) -> bool; + fn derives(&'static DOMClass) -> bool; } /// A trait to mark an IDL interface as deriving from another one. @@ -384,7 +384,7 @@ pub unsafe fn private_from_object(obj: *mut JSObject) -> *const libc::c_void { /// Get the `DOMClass` from `obj`, or `Err(())` if `obj` is not a DOM object. pub unsafe fn get_dom_class(obj: *mut JSObject) -> Result<&'static DOMClass, ()> { - use crate::dom::bindings::utils::DOMJSClass; + use dom::bindings::utils::DOMJSClass; use js::glue::GetProxyHandlerExtra; let clasp = get_object_class(obj); diff --git a/components/script/dom/bindings/error.rs b/components/script/dom/bindings/error.rs index bba99606ae7e..64b581f316df 100644 --- a/components/script/dom/bindings/error.rs +++ b/components/script/dom/bindings/error.rs @@ -7,26 +7,24 @@ #[cfg(feature = "js_backtrace")] use backtrace::Backtrace; #[cfg(feature = "js_backtrace")] -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; -use crate::dom::bindings::codegen::PrototypeList::proto_id_to_name; -use crate::dom::bindings::conversions::root_from_object; -use crate::dom::bindings::conversions::{ - ConversionResult, FromJSValConvertible, ToJSValConvertible, -}; -use crate::dom::bindings::str::USVString; -use crate::dom::domexception::{DOMErrorName, DOMException}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; +use dom::bindings::codegen::PrototypeList::proto_id_to_name; +use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; +use dom::bindings::conversions::root_from_object; +use dom::bindings::str::USVString; +use dom::domexception::{DOMErrorName, DOMException}; +use dom::globalscope::GlobalScope; use js::error::{throw_range_error, throw_type_error}; use js::jsapi::JSContext; use js::jsapi::JS_ClearPendingException; use js::jsapi::JS_IsExceptionPending; use js::jsval::UndefinedValue; +use js::rust::HandleObject; +use js::rust::MutableHandleValue; use js::rust::wrappers::JS_ErrorFromException; use js::rust::wrappers::JS_GetPendingException; use js::rust::wrappers::JS_SetPendingException; -use js::rust::HandleObject; -use js::rust::MutableHandleValue; use libc::c_uint; use std::slice::from_raw_parts; diff --git a/components/script/dom/bindings/htmlconstructor.rs b/components/script/dom/bindings/htmlconstructor.rs index f0f46aabeecf..7cbac28398f5 100644 --- a/components/script/dom/bindings/htmlconstructor.rs +++ b/components/script/dom/bindings/htmlconstructor.rs @@ -2,88 +2,89 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLAreaElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLAudioElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLBRElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLBodyElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDListElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDataElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDataListElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDirectoryElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDivElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLEmbedElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLFontElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLFormElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLFrameElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLHRElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLHeadElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLHeadingElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLImageElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLInputElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLLIElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLLabelElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLLegendElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLLinkElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLMapElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLMetaElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLMeterElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLModElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLOListElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLObjectElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLOptionElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLOutputElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLParamElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLPreElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLProgressElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLQuoteElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLScriptElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLSelectElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLSourceElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLSpanElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLStyleElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableCellElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableColElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTimeElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLTrackElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLUListElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLVideoElementBinding; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::conversions::DerivedFrom; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::create::create_native_html_element; -use crate::dom::customelementregistry::ConstructionStackEntry; -use crate::dom::element::{CustomElementState, Element, ElementCreator}; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::window::Window; -use crate::script_thread::ScriptThread; -use html5ever::interface::QualName; +use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding; +use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; +use dom::bindings::codegen::Bindings::HTMLAudioElementBinding; +use dom::bindings::codegen::Bindings::HTMLBRElementBinding; +use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; +use dom::bindings::codegen::Bindings::HTMLBodyElementBinding; +use dom::bindings::codegen::Bindings::HTMLButtonElementBinding; +use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; +use dom::bindings::codegen::Bindings::HTMLDListElementBinding; +use dom::bindings::codegen::Bindings::HTMLDataElementBinding; +use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; +use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; +use dom::bindings::codegen::Bindings::HTMLDialogElementBinding; +use dom::bindings::codegen::Bindings::HTMLDirectoryElementBinding; +use dom::bindings::codegen::Bindings::HTMLDivElementBinding; +use dom::bindings::codegen::Bindings::HTMLElementBinding; +use dom::bindings::codegen::Bindings::HTMLEmbedElementBinding; +use dom::bindings::codegen::Bindings::HTMLFieldSetElementBinding; +use dom::bindings::codegen::Bindings::HTMLFontElementBinding; +use dom::bindings::codegen::Bindings::HTMLFormElementBinding; +use dom::bindings::codegen::Bindings::HTMLFrameElementBinding; +use dom::bindings::codegen::Bindings::HTMLFrameSetElementBinding; +use dom::bindings::codegen::Bindings::HTMLHRElementBinding; +use dom::bindings::codegen::Bindings::HTMLHeadElementBinding; +use dom::bindings::codegen::Bindings::HTMLHeadingElementBinding; +use dom::bindings::codegen::Bindings::HTMLHtmlElementBinding; +use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding; +use dom::bindings::codegen::Bindings::HTMLImageElementBinding; +use dom::bindings::codegen::Bindings::HTMLInputElementBinding; +use dom::bindings::codegen::Bindings::HTMLLIElementBinding; +use dom::bindings::codegen::Bindings::HTMLLabelElementBinding; +use dom::bindings::codegen::Bindings::HTMLLegendElementBinding; +use dom::bindings::codegen::Bindings::HTMLLinkElementBinding; +use dom::bindings::codegen::Bindings::HTMLMapElementBinding; +use dom::bindings::codegen::Bindings::HTMLMetaElementBinding; +use dom::bindings::codegen::Bindings::HTMLMeterElementBinding; +use dom::bindings::codegen::Bindings::HTMLModElementBinding; +use dom::bindings::codegen::Bindings::HTMLOListElementBinding; +use dom::bindings::codegen::Bindings::HTMLObjectElementBinding; +use dom::bindings::codegen::Bindings::HTMLOptGroupElementBinding; +use dom::bindings::codegen::Bindings::HTMLOptionElementBinding; +use dom::bindings::codegen::Bindings::HTMLOutputElementBinding; +use dom::bindings::codegen::Bindings::HTMLParagraphElementBinding; +use dom::bindings::codegen::Bindings::HTMLParamElementBinding; +use dom::bindings::codegen::Bindings::HTMLPreElementBinding; +use dom::bindings::codegen::Bindings::HTMLProgressElementBinding; +use dom::bindings::codegen::Bindings::HTMLQuoteElementBinding; +use dom::bindings::codegen::Bindings::HTMLScriptElementBinding; +use dom::bindings::codegen::Bindings::HTMLSelectElementBinding; +use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; +use dom::bindings::codegen::Bindings::HTMLSpanElementBinding; +use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableCaptionElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableColElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableDataCellElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableHeaderCellElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableRowElementBinding; +use dom::bindings::codegen::Bindings::HTMLTableSectionElementBinding; +use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding; +use dom::bindings::codegen::Bindings::HTMLTextAreaElementBinding; +use dom::bindings::codegen::Bindings::HTMLTimeElementBinding; +use dom::bindings::codegen::Bindings::HTMLTitleElementBinding; +use dom::bindings::codegen::Bindings::HTMLTrackElementBinding; +use dom::bindings::codegen::Bindings::HTMLUListElementBinding; +use dom::bindings::codegen::Bindings::HTMLVideoElementBinding; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::root::DomRoot; +use dom::create::create_native_html_element; +use dom::customelementregistry::ConstructionStackEntry; +use dom::element::{CustomElementState, Element, ElementCreator}; +use dom::htmlelement::HTMLElement; +use dom::window::Window; use html5ever::LocalName; +use html5ever::interface::QualName; use js::glue::UnwrapObject; use js::jsapi::{CallArgs, CurrentGlobalOrNull}; use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; use js::rust::HandleObject; use js::rust::MutableHandleObject; +use script_thread::ScriptThread; use std::ptr; // https://html.spec.whatwg.org/multipage/#htmlconstructor @@ -309,11 +310,11 @@ pub fn get_constructor_object_from_local_name( local_name!("sup") => get_constructor!(HTMLElementBinding), local_name!("table") => get_constructor!(HTMLTableElementBinding), local_name!("tbody") => get_constructor!(HTMLTableSectionElementBinding), - local_name!("td") => get_constructor!(HTMLTableCellElementBinding), + local_name!("td") => get_constructor!(HTMLTableDataCellElementBinding), local_name!("template") => get_constructor!(HTMLTemplateElementBinding), local_name!("textarea") => get_constructor!(HTMLTextAreaElementBinding), local_name!("tfoot") => get_constructor!(HTMLTableSectionElementBinding), - local_name!("th") => get_constructor!(HTMLTableCellElementBinding), + local_name!("th") => get_constructor!(HTMLTableHeaderCellElementBinding), local_name!("thead") => get_constructor!(HTMLTableSectionElementBinding), local_name!("time") => get_constructor!(HTMLTimeElementBinding), local_name!("title") => get_constructor!(HTMLTitleElementBinding), diff --git a/components/script/dom/bindings/inheritance.rs b/components/script/dom/bindings/inheritance.rs index 888e0525fead..eaf394e594d6 100644 --- a/components/script/dom/bindings/inheritance.rs +++ b/components/script/dom/bindings/inheritance.rs @@ -4,11 +4,11 @@ //! The `Castable` trait. -pub use crate::dom::bindings::codegen::InheritTypes::*; +pub use dom::bindings::codegen::InheritTypes::*; -use crate::dom::bindings::conversions::get_dom_class; -use crate::dom::bindings::conversions::{DerivedFrom, IDLInterface}; -use crate::dom::bindings::reflector::DomObject; +use dom::bindings::conversions::{DerivedFrom, IDLInterface}; +use dom::bindings::conversions::get_dom_class; +use dom::bindings::reflector::DomObject; use std::mem; /// A trait to hold the cast functions of IDL interfaces that either derive diff --git a/components/script/dom/bindings/interface.rs b/components/script/dom/bindings/interface.rs index c7de37a202b0..210e9ae55768 100644 --- a/components/script/dom/bindings/interface.rs +++ b/components/script/dom/bindings/interface.rs @@ -4,37 +4,34 @@ //! Machinery to initialise interface prototype objects and interface objects. -use crate::dom::bindings::codegen::InterfaceObjectMap::Globals; -use crate::dom::bindings::codegen::PrototypeList; -use crate::dom::bindings::constant::{define_constants, ConstantSpec}; -use crate::dom::bindings::conversions::{get_dom_class, DOM_OBJECT_SLOT}; -use crate::dom::bindings::guard::Guard; -use crate::dom::bindings::utils::{ - get_proto_or_iface_array, ProtoOrIfaceArray, DOM_PROTOTYPE_SLOT, -}; +use dom::bindings::codegen::InterfaceObjectMap::Globals; +use dom::bindings::codegen::PrototypeList; +use dom::bindings::constant::{define_constants, ConstantSpec}; +use dom::bindings::conversions::{get_dom_class, DOM_OBJECT_SLOT}; +use dom::bindings::guard::Guard; +use dom::bindings::utils::{get_proto_or_iface_array, ProtoOrIfaceArray, DOM_PROTOTYPE_SLOT}; use js::error::throw_type_error; use js::glue::{UncheckedUnwrapObject, RUST_SYMBOL_TO_JSID}; -use js::jsapi::HandleObject as RawHandleObject; -use js::jsapi::MutableHandleValue as RawMutableHandleValue; use js::jsapi::{Class, ClassOps, CompartmentOptions}; use js::jsapi::{GetGlobalForObjectCrossCompartment, GetWellKnownSymbol}; -use js::jsapi::{ - JSAutoCompartment, JSClass, JSContext, JSFunctionSpec, JSObject, JSFUN_CONSTRUCTOR, -}; +use js::jsapi::{JSAutoCompartment, JSClass, JSContext, JSFunctionSpec, JSObject, JSFUN_CONSTRUCTOR}; +use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; use js::jsapi::{JSPropertySpec, JSString, JSTracer, JS_AtomizeAndPinString}; use js::jsapi::{JS_GetFunctionObject, JS_NewFunction, JS_NewGlobalObject}; use js::jsapi::{JS_NewObject, JS_NewPlainObject}; use js::jsapi::{JS_NewStringCopyN, JS_SetReservedSlot}; use js::jsapi::{ObjectOps, OnNewGlobalHookOption, SymbolCode}; use js::jsapi::{TrueHandleValue, Value}; -use js::jsapi::{JSPROP_PERMANENT, JSPROP_READONLY, JSPROP_RESOLVING}; +use js::jsapi::HandleObject as RawHandleObject; +use js::jsapi::MutableHandleValue as RawMutableHandleValue; use js::jsval::{JSVal, PrivateValue}; +use js::rust::{HandleObject, HandleValue, MutableHandleObject}; +use js::rust::{define_methods, define_properties, get_object_class}; use js::rust::wrappers::{JS_DefineProperty, JS_DefineProperty2}; use js::rust::wrappers::{JS_DefineProperty3, JS_DefineProperty4, JS_DefinePropertyById4}; use js::rust::wrappers::{JS_FireOnNewGlobalObject, JS_GetPrototype}; use js::rust::wrappers::{JS_LinkConstructorAndPrototype, JS_NewObjectWithUniqueType}; -use js::rust::{define_methods, define_properties, get_object_class}; -use js::rust::{HandleObject, HandleValue, MutableHandleObject}; +use libc; use std::convert::TryFrom; use std::ptr; diff --git a/components/script/dom/bindings/iterable.rs b/components/script/dom/bindings/iterable.rs index b75dba9591b9..488714d3d0bc 100644 --- a/components/script/dom/bindings/iterable.rs +++ b/components/script/dom/bindings/iterable.rs @@ -6,13 +6,13 @@ //! Implementation of `iterable<...>` and `iterable<..., ...>` WebIDL declarations. -use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; -use crate::dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::trace::{JSTraceable, RootedTraceableBox}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyAndValueResult; +use dom::bindings::codegen::Bindings::IterableIteratorBinding::IterableKeyOrValueResult; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::trace::{JSTraceable, RootedTraceableBox}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::conversions::ToJSValConvertible; use js::jsapi::{Heap, JSContext, JSObject}; diff --git a/components/script/dom/bindings/mozmap.rs b/components/script/dom/bindings/mozmap.rs index 4d74a6405b04..68ea9fa382d0 100644 --- a/components/script/dom/bindings/mozmap.rs +++ b/components/script/dom/bindings/mozmap.rs @@ -4,24 +4,24 @@ //! The `MozMap` (open-ended dictionary) type. -use crate::dom::bindings::conversions::jsid_to_string; -use crate::dom::bindings::error::report_pending_exception; -use crate::dom::bindings::str::DOMString; +use dom::bindings::conversions::jsid_to_string; +use dom::bindings::error::report_pending_exception; +use dom::bindings::str::DOMString; use js::conversions::{ConversionResult, FromJSValConvertible, ToJSValConvertible}; use js::jsapi::JSContext; -use js::jsapi::JS_NewPlainObject; use js::jsapi::JSITER_HIDDEN; use js::jsapi::JSITER_OWNONLY; use js::jsapi::JSITER_SYMBOLS; use js::jsapi::JSPROP_ENUMERATE; +use js::jsapi::JS_NewPlainObject; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; -use js::rust::wrappers::GetPropertyKeys; -use js::rust::wrappers::JS_DefineUCProperty2; -use js::rust::wrappers::JS_GetPropertyById; use js::rust::HandleValue; use js::rust::IdVector; use js::rust::MutableHandleValue; +use js::rust::wrappers::GetPropertyKeys; +use js::rust::wrappers::JS_DefineUCProperty2; +use js::rust::wrappers::JS_GetPropertyById; use std::collections::HashMap; use std::ops::Deref; diff --git a/components/script/dom/bindings/namespace.rs b/components/script/dom/bindings/namespace.rs index bb20e7b33200..64b67b33e1e6 100644 --- a/components/script/dom/bindings/namespace.rs +++ b/components/script/dom/bindings/namespace.rs @@ -4,10 +4,11 @@ //! Machinery to initialise namespace objects. -use crate::dom::bindings::guard::Guard; -use crate::dom::bindings::interface::{create_object, define_on_global_object}; +use dom::bindings::guard::Guard; +use dom::bindings::interface::{create_object, define_on_global_object}; use js::jsapi::{JSClass, JSContext, JSFunctionSpec}; use js::rust::{HandleObject, MutableHandleObject}; +use libc; /// The class of a namespace object. #[derive(Clone, Copy)] diff --git a/components/script/dom/bindings/proxyhandler.rs b/components/script/dom/bindings/proxyhandler.rs index a4584f2daa10..86b7d81667c9 100644 --- a/components/script/dom/bindings/proxyhandler.rs +++ b/components/script/dom/bindings/proxyhandler.rs @@ -6,11 +6,13 @@ #![deny(missing_docs)] -use crate::dom::bindings::conversions::is_dom_proxy; -use crate::dom::bindings::utils::delete_property_by_id; -use js::glue::InvokeGetOwnPropertyDescriptor; +use dom::bindings::conversions::is_dom_proxy; +use dom::bindings::utils::delete_property_by_id; use js::glue::{GetProxyHandler, GetProxyHandlerFamily}; use js::glue::{GetProxyPrivate, SetProxyPrivate}; +use js::glue::InvokeGetOwnPropertyDescriptor; +use js::jsapi::{DOMProxyShadowsResult, JSContext, JSObject, PropertyDescriptor}; +use js::jsapi::{JSErrNum, SetDOMProxyInformation}; use js::jsapi::GetObjectProto; use js::jsapi::GetStaticPrototype; use js::jsapi::Handle as RawHandle; @@ -21,13 +23,11 @@ use js::jsapi::JS_GetPropertyDescriptorById; use js::jsapi::MutableHandle as RawMutableHandle; use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsapi::ObjectOpResult; -use js::jsapi::{DOMProxyShadowsResult, JSContext, JSObject, PropertyDescriptor}; -use js::jsapi::{JSErrNum, SetDOMProxyInformation}; use js::jsval::ObjectValue; use js::jsval::UndefinedValue; +use js::rust::{Handle, HandleObject, MutableHandle, MutableHandleObject}; use js::rust::wrappers::JS_AlreadyHasOwnPropertyById; use js::rust::wrappers::JS_NewObjectWithGivenProto; -use js::rust::{Handle, HandleObject, MutableHandle, MutableHandleObject}; use std::ptr; /// Determine if this id shadows any existing properties for this proxy. diff --git a/components/script/dom/bindings/refcounted.rs b/components/script/dom/bindings/refcounted.rs index 636a393c83b9..11a422a2f3f3 100644 --- a/components/script/dom/bindings/refcounted.rs +++ b/components/script/dom/bindings/refcounted.rs @@ -22,14 +22,14 @@ //! its hash table during the next GC. During GC, the entries of the hash table are counted //! as JS roots. -use crate::dom::bindings::conversions::ToJSValConvertible; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::reflector::{DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::trace::trace_reflector; -use crate::dom::promise::Promise; -use crate::task::TaskOnce; +use dom::bindings::conversions::ToJSValConvertible; +use dom::bindings::error::Error; +use dom::bindings::reflector::{DomObject, Reflector}; +use dom::bindings::root::DomRoot; +use dom::bindings::trace::trace_reflector; +use dom::promise::Promise; use js::jsapi::JSTracer; +use libc; use std::cell::RefCell; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::hash_map::HashMap; @@ -37,13 +37,14 @@ use std::hash::Hash; use std::marker::PhantomData; use std::rc::Rc; use std::sync::{Arc, Weak}; +use task::TaskOnce; #[allow(missing_docs)] // FIXME mod dummy { // Attributes don’t apply through the macro. - use super::LiveDOMReferences; use std::cell::RefCell; use std::rc::Rc; + use super::LiveDOMReferences; thread_local!(pub static LIVE_REFERENCES: Rc>> = Rc::new(RefCell::new(None))); } @@ -223,12 +224,6 @@ impl LiveDOMReferences { }); } - pub fn destruct() { - LIVE_REFERENCES.with(|ref r| { - *r.borrow_mut() = None; - }); - } - #[allow(unrooted_must_root)] fn addref_promise(&self, promise: Rc) { let mut table = self.promise_table.borrow_mut(); diff --git a/components/script/dom/bindings/reflector.rs b/components/script/dom/bindings/reflector.rs index 0d27a5206db1..2bf1983d40e4 100644 --- a/components/script/dom/bindings/reflector.rs +++ b/components/script/dom/bindings/reflector.rs @@ -4,10 +4,10 @@ //! The `Reflector` struct. -use crate::dom::bindings::conversions::DerivedFrom; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; -use js::jsapi::{Heap, JSContext, JSObject}; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; +use js::jsapi::{JSContext, JSObject, Heap}; use js::rust::HandleObject; use std::default::Default; diff --git a/components/script/dom/bindings/root.rs b/components/script/dom/bindings/root.rs index 5318eb11e4de..d974e75737c0 100644 --- a/components/script/dom/bindings/root.rs +++ b/components/script/dom/bindings/root.rs @@ -24,13 +24,13 @@ //! originating `DomRoot`. //! -use crate::dom::bindings::conversions::DerivedFrom; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{DomObject, Reflector}; -use crate::dom::bindings::trace::trace_reflector; -use crate::dom::bindings::trace::JSTraceable; -use crate::dom::node::Node; -use js::jsapi::{Heap, JSObject, JSTracer}; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, Reflector}; +use dom::bindings::trace::JSTraceable; +use dom::bindings::trace::trace_reflector; +use dom::node::Node; +use js::jsapi::{JSObject, JSTracer, Heap}; use js::rust::GCMethods; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use mitochondria::OnceCell; @@ -78,14 +78,14 @@ where pub unsafe trait StableTraceObject { /// Returns a stable trace object which address won't change for the whole /// lifetime of the value. - fn stable_trace_object(&self) -> *const dyn JSTraceable; + fn stable_trace_object(&self) -> *const JSTraceable; } unsafe impl StableTraceObject for Dom where T: DomObject, { - fn stable_trace_object<'a>(&'a self) -> *const dyn JSTraceable { + fn stable_trace_object<'a>(&'a self) -> *const JSTraceable { // The JSTraceable impl for Reflector doesn't actually do anything, // so we need this shenanigan to actually trace the reflector of the // T pointer in Dom. @@ -198,7 +198,7 @@ where /// See also [*Exact Stack Rooting - Storing a GCPointer on the CStack*] /// (https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Internals/GC/Exact_Stack_Rooting). pub struct RootCollection { - roots: UnsafeCell>, + roots: UnsafeCell>, } thread_local!(static STACK_ROOTS: Cell> = Cell::new(None)); @@ -228,13 +228,13 @@ impl RootCollection { } /// Starts tracking a trace object. - unsafe fn root(&self, object: *const dyn JSTraceable) { + unsafe fn root(&self, object: *const JSTraceable) { debug_assert!(thread_state::get().is_script()); (*self.roots.get()).push(object); } /// Stops tracking a trace object, asserting if it isn't found. - unsafe fn unroot(&self, object: *const dyn JSTraceable) { + unsafe fn unroot(&self, object: *const JSTraceable) { debug_assert!(thread_state::get().is_script()); let roots = &mut *self.roots.get(); match roots.iter().rposition(|r| *r == object) { diff --git a/components/script/dom/bindings/settings_stack.rs b/components/script/dom/bindings/settings_stack.rs index aee67a3da97b..e5efea05e982 100644 --- a/components/script/dom/bindings/settings_stack.rs +++ b/components/script/dom/bindings/settings_stack.rs @@ -2,9 +2,9 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::trace::JSTraceable; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::trace::JSTraceable; +use dom::globalscope::GlobalScope; use js::jsapi::GetScriptedCallerGlobal; use js::jsapi::HideScriptedCaller; use js::jsapi::JSTracer; @@ -94,8 +94,7 @@ pub fn entry_global() -> DomRoot { .rev() .find(|entry| entry.kind == StackEntryKind::Entry) .map(|entry| DomRoot::from_ref(&*entry.global)) - }) - .unwrap() + }).unwrap() } /// RAII struct that pushes and pops entries from the script settings stack. diff --git a/components/script/dom/bindings/str.rs b/components/script/dom/bindings/str.rs index 9f0380265623..e52cf7755a37 100644 --- a/components/script/dom/bindings/str.rs +++ b/components/script/dom/bindings/str.rs @@ -4,8 +4,8 @@ //! The `ByteString` struct. -use chrono::prelude::{Utc, Weekday}; use chrono::{Datelike, TimeZone}; +use chrono::prelude::{Weekday, Utc}; use cssparser::CowRcStr; use html5ever::{LocalName, Namespace}; use servo_atoms::Atom; diff --git a/components/script/dom/bindings/structuredclone.rs b/components/script/dom/bindings/structuredclone.rs index d4cc8c1cdae3..c4a68547247b 100644 --- a/components/script/dom/bindings/structuredclone.rs +++ b/components/script/dom/bindings/structuredclone.rs @@ -5,30 +5,30 @@ //! This module implements structured cloning, as defined by [HTML] //! (https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data). -use crate::dom::bindings::conversions::root_from_handleobject; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::DomRoot; -use crate::dom::blob::{Blob, BlobImpl}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::conversions::root_from_handleobject; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::DomRoot; +use dom::blob::{Blob, BlobImpl}; +use dom::globalscope::GlobalScope; use js::glue::CopyJSStructuredCloneData; use js::glue::DeleteJSAutoStructuredCloneBuffer; use js::glue::GetLengthOfJSStructuredCloneData; use js::glue::NewJSAutoStructuredCloneBuffer; use js::glue::WriteBytesToJSStructuredCloneData; +use js::jsapi::{JSAutoCompartment, JSContext}; +use js::jsapi::{JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter}; +use js::jsapi::{JS_ClearPendingException, JSObject}; +use js::jsapi::{JS_ReadBytes, JS_WriteBytes}; +use js::jsapi::{JS_ReadUint32Pair, JS_WriteUint32Pair}; use js::jsapi::CloneDataPolicy; use js::jsapi::HandleObject as RawHandleObject; +use js::jsapi::JS_STRUCTURED_CLONE_VERSION; use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsapi::StructuredCloneScope; use js::jsapi::TransferableOwnership; -use js::jsapi::JS_STRUCTURED_CLONE_VERSION; -use js::jsapi::{JSAutoCompartment, JSContext}; -use js::jsapi::{JSObject, JS_ClearPendingException}; -use js::jsapi::{JSStructuredCloneCallbacks, JSStructuredCloneReader, JSStructuredCloneWriter}; -use js::jsapi::{JS_ReadBytes, JS_WriteBytes}; -use js::jsapi::{JS_ReadUint32Pair, JS_WriteUint32Pair}; -use js::rust::wrappers::{JS_ReadStructuredClone, JS_WriteStructuredClone}; use js::rust::{Handle, HandleValue, MutableHandleValue}; +use js::rust::wrappers::{JS_WriteStructuredClone, JS_ReadStructuredClone}; use libc::size_t; use std::os::raw; use std::ptr; diff --git a/components/script/dom/bindings/trace.rs b/components/script/dom/bindings/trace.rs index d8d3000d037b..2c395094e7fd 100644 --- a/components/script/dom/bindings/trace.rs +++ b/components/script/dom/bindings/trace.rs @@ -30,36 +30,34 @@ //! `JSTraceable` to a datatype. use app_units::Au; -use canvas_traits::canvas::{ - CanvasGradientStop, CanvasId, LinearGradientStyle, RadialGradientStyle, -}; +use canvas_traits::canvas::{CanvasGradientStop, CanvasId, LinearGradientStyle, RadialGradientStyle}; use canvas_traits::canvas::{CompositionOrBlending, LineCapStyle, LineJoinStyle, RepetitionStyle}; use canvas_traits::webgl::{ActiveAttribInfo, ActiveUniformInfo, WebGLBufferId, WebGLChan}; use canvas_traits::webgl::{WebGLContextShareMode, WebGLError, WebGLFramebufferId, WebGLMsgSender}; use canvas_traits::webgl::{WebGLPipeline, WebGLProgramId, WebGLReceiver, WebGLRenderbufferId}; use canvas_traits::webgl::{WebGLSLVersion, WebGLSender, WebGLShaderId, WebGLTextureId}; use canvas_traits::webgl::{WebGLVersion, WebGLVertexArrayId}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::bindings::utils::WindowProxyHandler; -use crate::dom::document::PendingRestyle; -use crate::dom::htmlimageelement::SourceSet; -use crate::dom::htmlmediaelement::MediaFrameRenderer; use cssparser::RGBA; use devtools_traits::{CSSError, TimelineMarkerType, WorkerId}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::error::Error; +use dom::bindings::refcounted::{Trusted, TrustedPromise}; +use dom::bindings::reflector::{DomObject, Reflector}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::{DOMString, USVString}; +use dom::bindings::utils::WindowProxyHandler; +use dom::document::PendingRestyle; +use dom::htmlimageelement::SourceSet; use encoding_rs::{Decoder, Encoding}; +use euclid::{Transform2D, Transform3D, Point2D, Vector2D, Rect, TypedSize2D, TypedScale}; use euclid::Length as EuclidLength; -use euclid::{Point2D, Rect, Transform2D, Transform3D, TypedScale, TypedSize2D, Vector2D}; +use html5ever::{Prefix, LocalName, Namespace, QualName}; use html5ever::buffer_queue::BufferQueue; use html5ever::tendril::IncompleteUtf8; -use html5ever::{LocalName, Namespace, Prefix, QualName}; -use http::header::HeaderMap; -use hyper::Method; -use hyper::StatusCode; +use hyper::header::Headers; +use hyper::method::Method; +use hyper::mime::Mime; +use hyper::status::StatusCode; use ipc_channel::ipc::{IpcReceiver, IpcSender}; use js::glue::{CallObjectTracer, CallValueTracer}; use js::jsapi::{GCTraceKindToAscii, Heap, JSObject, JSTracer, TraceKind}; @@ -68,41 +66,36 @@ use js::rust::{GCMethods, Handle, Runtime}; use js::typedarray::TypedArray; use js::typedarray::TypedArrayElement; use metrics::{InteractiveMetrics, InteractiveWindow}; -use mime::Mime; -use msg::constellation_msg::{ - BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId, -}; +use msg::constellation_msg::{BrowsingContextId, HistoryStateId, PipelineId, TopLevelBrowsingContextId}; +use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads}; use net_traits::filemanager_thread::RelativePos; use net_traits::image::base::{Image, ImageMetadata}; use net_traits::image_cache::{ImageCache, PendingImageId}; use net_traits::request::{Request, RequestInit}; -use net_traits::response::HttpsState; use net_traits::response::{Response, ResponseBody}; +use net_traits::response::HttpsState; use net_traits::storage_thread::StorageType; -use net_traits::{Metadata, NetworkError, ReferrerPolicy, ResourceThreads}; use offscreen_gl_context::GLLimits; use profile_traits::mem::ProfilerChan as MemProfilerChan; use profile_traits::time::ProfilerChan as TimeProfilerChan; +use script_layout_interface::OpaqueStyleAndLayoutData; use script_layout_interface::reporter::CSSErrorReporter; use script_layout_interface::rpc::LayoutRPC; -use script_layout_interface::OpaqueStyleAndLayoutData; -use script_traits::DrawAPaintImageResult; use script_traits::{DocumentActivity, ScriptToConstellationChan, TimerEventId, TimerSource}; use script_traits::{UntrustedNodeAddress, WindowSizeData, WindowSizeType}; +use script_traits::DrawAPaintImageResult; use selectors::matching::ElementSelectorFlags; use serde::{Deserialize, Serialize}; use servo_arc::Arc as ServoArc; use servo_atoms::Atom; use servo_channel::{Receiver, Sender}; +use servo_media::Backend; use servo_media::audio::analyser_node::AnalysisEngine; use servo_media::audio::buffer_source_node::AudioBuffer; use servo_media::audio::context::AudioContext; use servo_media::audio::graph::NodeId; use servo_media::audio::panner_node::{DistanceModel, PanningModel}; use servo_media::audio::param::ParamType; -use servo_media::player::Player; -use servo_media::Backend; -use servo_media::Error as ServoMediaError; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use smallvec::SmallVec; use std::cell::{Cell, RefCell, UnsafeCell}; @@ -111,24 +104,24 @@ use std::hash::{BuildHasher, Hash}; use std::ops::{Deref, DerefMut}; use std::path::PathBuf; use std::rc::Rc; +use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicUsize}; -use std::sync::{Arc, Mutex}; -use std::time::{Instant, SystemTime}; +use std::time::{SystemTime, Instant}; use style::attr::{AttrIdentifier, AttrValue, LengthOrPercentageOrAuto}; use style::context::QuirksMode; use style::element_state::*; use style::media_queries::MediaList; use style::properties::PropertyDeclarationBlock; use style::selector_parser::{PseudoElement, Snapshot}; -use style::shared_lock::{Locked as StyleLocked, SharedRwLock as StyleSharedRwLock}; +use style::shared_lock::{SharedRwLock as StyleSharedRwLock, Locked as StyleLocked}; use style::stylesheet_set::DocumentStylesheetSet; -use style::stylesheets::keyframes_rule::Keyframe; use style::stylesheets::{CssRules, FontFaceRule, KeyframesRule, MediaRule, Stylesheet}; -use style::stylesheets::{ImportRule, NamespaceRule, StyleRule, SupportsRule, ViewportRule}; +use style::stylesheets::{NamespaceRule, StyleRule, ImportRule, SupportsRule, ViewportRule}; +use style::stylesheets::keyframes_rule::Keyframe; use style::values::specified::Length; use time::Duration; use uuid::Uuid; -use webrender_api::{DocumentId, ImageKey, RenderApiSender}; +use webrender_api::{DocumentId, ImageKey}; use webvr_traits::WebVRGamepadHand; /// A trait to allow tracing (only) DOM objects. @@ -268,13 +261,7 @@ unsafe impl JSTraceable for VecDeque { } } -unsafe impl JSTraceable for (A, B, C, D) -where - A: JSTraceable, - B: JSTraceable, - C: JSTraceable, - D: JSTraceable, -{ +unsafe impl JSTraceable for (T, T, T, T) { unsafe fn trace(&self, trc: *mut JSTracer) { self.0.trace(trc); self.1.trace(trc); @@ -375,7 +362,7 @@ unsafe_no_jsmanaged_fields!(usize, u8, u16, u32, u64); unsafe_no_jsmanaged_fields!(isize, i8, i16, i32, i64); unsafe_no_jsmanaged_fields!(Error); unsafe_no_jsmanaged_fields!(ServoUrl, ImmutableOrigin, MutableOrigin); -unsafe_no_jsmanaged_fields!(Image, ImageMetadata, dyn ImageCache, PendingImageId); +unsafe_no_jsmanaged_fields!(Image, ImageMetadata, ImageCache, PendingImageId); unsafe_no_jsmanaged_fields!(Metadata); unsafe_no_jsmanaged_fields!(NetworkError); unsafe_no_jsmanaged_fields!(Atom, Prefix, LocalName, Namespace, QualName); @@ -395,7 +382,7 @@ unsafe_no_jsmanaged_fields!(TimelineMarkerType); unsafe_no_jsmanaged_fields!(WorkerId); unsafe_no_jsmanaged_fields!(BufferQueue, QuirksMode, IncompleteUtf8); unsafe_no_jsmanaged_fields!(Runtime); -unsafe_no_jsmanaged_fields!(HeaderMap, Method); +unsafe_no_jsmanaged_fields!(Headers, Method); unsafe_no_jsmanaged_fields!(WindowProxyHandler); unsafe_no_jsmanaged_fields!(UntrustedNodeAddress); unsafe_no_jsmanaged_fields!(LengthOrPercentageOrAuto); @@ -461,9 +448,6 @@ unsafe_no_jsmanaged_fields!(AudioBuffer); unsafe_no_jsmanaged_fields!(AudioContext); unsafe_no_jsmanaged_fields!(NodeId); unsafe_no_jsmanaged_fields!(AnalysisEngine, DistanceModel, PanningModel, ParamType); -unsafe_no_jsmanaged_fields!(dyn Player); -unsafe_no_jsmanaged_fields!(Mutex); -unsafe_no_jsmanaged_fields!(RenderApiSender); unsafe impl<'a> JSTraceable for &'a str { #[inline] @@ -497,7 +481,7 @@ where } // Safe thanks to the Send bound. -unsafe impl JSTraceable for Box { +unsafe impl JSTraceable for Box { #[inline] unsafe fn trace(&self, _: *mut JSTracer) { // Do nothing @@ -632,13 +616,6 @@ unsafe impl JSTraceable for TypedSize2D { } } -unsafe impl JSTraceable for TypedSize2D { - #[inline] - unsafe fn trace(&self, _trc: *mut JSTracer) { - // Do nothing - } -} - unsafe impl JSTraceable for StyleLocked { unsafe fn trace(&self, _trc: *mut JSTracer) { // Do nothing. @@ -733,7 +710,7 @@ where /// Holds a set of JSTraceables that need to be rooted struct RootedTraceableSet { - set: Vec<*const dyn JSTraceable>, + set: Vec<*const JSTraceable>, } thread_local!(/// TLV Holds a set of JSTraceables that need to be rooted @@ -744,7 +721,7 @@ impl RootedTraceableSet { RootedTraceableSet { set: vec![] } } - unsafe fn remove(traceable: *const dyn JSTraceable) { + unsafe fn remove(traceable: *const JSTraceable) { ROOTED_TRACEABLES.with(|ref traceables| { let mut traceables = traceables.borrow_mut(); let idx = match traceables.set.iter().rposition(|x| *x == traceable) { @@ -755,7 +732,7 @@ impl RootedTraceableSet { }); } - unsafe fn add(traceable: *const dyn JSTraceable) { + unsafe fn add(traceable: *const JSTraceable) { ROOTED_TRACEABLES.with(|ref traceables| { traceables.borrow_mut().set.push(traceable); }) diff --git a/components/script/dom/bindings/utils.rs b/components/script/dom/bindings/utils.rs index e2591566ceed..7366401af513 100644 --- a/components/script/dom/bindings/utils.rs +++ b/components/script/dom/bindings/utils.rs @@ -4,29 +4,33 @@ //! Various utilities to glue JavaScript and the DOM implementation together. -use crate::dom::bindings::codegen::InterfaceObjectMap; -use crate::dom::bindings::codegen::PrototypeList; -use crate::dom::bindings::codegen::PrototypeList::{MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH}; -use crate::dom::bindings::conversions::{jsstring_to_str, private_from_proto_check}; -use crate::dom::bindings::error::throw_invalid_this; -use crate::dom::bindings::inheritance::TopTypeId; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::trace_object; -use crate::dom::windowproxy; +use dom::bindings::codegen::InterfaceObjectMap; +use dom::bindings::codegen::PrototypeList; +use dom::bindings::codegen::PrototypeList::{MAX_PROTO_CHAIN_LENGTH, PROTO_OR_IFACE_LENGTH}; +use dom::bindings::conversions::{jsstring_to_str, private_from_proto_check}; +use dom::bindings::error::throw_invalid_this; +use dom::bindings::inheritance::TopTypeId; +use dom::bindings::str::DOMString; +use dom::bindings::trace::trace_object; +use dom::windowproxy; +use js; +use js::JS_CALLEE; use js::glue::{CallJitGetterOp, CallJitMethodOp, CallJitSetterOp, IsWrapper}; use js::glue::{GetCrossCompartmentWrapper, JS_GetReservedSlot, WrapperNew}; -use js::glue::{UnwrapObject, RUST_JSID_TO_INT, RUST_JSID_TO_STRING}; use js::glue::{RUST_FUNCTION_VALUE_TO_JITINFO, RUST_JSID_IS_INT, RUST_JSID_IS_STRING}; -use js::jsapi::HandleId as RawHandleId; -use js::jsapi::HandleObject as RawHandleObject; -use js::jsapi::MutableHandleObject as RawMutableHandleObject; +use js::glue::{RUST_JSID_TO_INT, RUST_JSID_TO_STRING, UnwrapObject}; use js::jsapi::{CallArgs, DOMCallbacks, GetGlobalForObjectCrossCompartment}; use js::jsapi::{Heap, JSAutoCompartment, JSContext}; use js::jsapi::{JSJitInfo, JSObject, JSTracer, JSWrapObjectCallbacks}; use js::jsapi::{JS_EnumerateStandardClasses, JS_GetLatin1StringCharsAndLength}; use js::jsapi::{JS_IsExceptionPending, JS_IsGlobalObject}; use js::jsapi::{JS_ResolveStandardClass, JS_StringHasLatin1Chars, ObjectOpResult}; +use js::jsapi::HandleId as RawHandleId; +use js::jsapi::HandleObject as RawHandleObject; +use js::jsapi::MutableHandleObject as RawMutableHandleObject; use js::jsval::{JSVal, UndefinedValue}; +use js::rust::{GCMethods, ToString, ToWindowProxyIfWindow, get_object_class, is_dom_class}; +use js::rust::{Handle, HandleId, HandleObject, HandleValue, MutableHandleValue}; use js::rust::wrappers::JS_DeletePropertyById; use js::rust::wrappers::JS_ForwardGetPropertyTo; use js::rust::wrappers::JS_GetProperty; @@ -34,9 +38,7 @@ use js::rust::wrappers::JS_GetPrototype; use js::rust::wrappers::JS_HasProperty; use js::rust::wrappers::JS_HasPropertyById; use js::rust::wrappers::JS_SetProperty; -use js::rust::{get_object_class, is_dom_class, GCMethods, ToString, ToWindowProxyIfWindow}; -use js::rust::{Handle, HandleId, HandleObject, HandleValue, MutableHandleValue}; -use js::JS_CALLEE; +use libc; use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use std::ffi::CString; use std::os::raw::{c_char, c_void}; @@ -170,20 +172,19 @@ pub fn get_array_index_from_id(_cx: *mut JSContext, id: HandleId) -> Option None } // if id is length atom, -1, otherwise - // return if JSID_IS_ATOM(id) { - // let atom = JSID_TO_ATOM(id); - // //let s = *GetAtomChars(id); - // if s > 'a' && s < 'z' { - // return -1; - // } - // - // let i = 0; - // let str = AtomToLinearString(JSID_TO_ATOM(id)); - // return if StringIsArray(str, &mut i) != 0 { i } else { -1 } - // } else { - // IdToInt32(cx, id); - // } -} + /*return if JSID_IS_ATOM(id) { + let atom = JSID_TO_ATOM(id); + //let s = *GetAtomChars(id); + if s > 'a' && s < 'z' { + return -1; + } + + let i = 0; + let str = AtomToLinearString(JSID_TO_ATOM(id)); + return if StringIsArray(str, &mut i) != 0 { i } else { -1 } + } else { + IdToInt32(cx, id); + }*/} /// Find the enum equivelent of a string given by `v` in `pairs`. /// Returns `Err(())` on JSAPI failure (there is a pending exception), and diff --git a/components/script/dom/bindings/weakref.rs b/components/script/dom/bindings/weakref.rs index 2a9e176af6e7..aed0d9ec6f8b 100644 --- a/components/script/dom/bindings/weakref.rs +++ b/components/script/dom/bindings/weakref.rs @@ -11,10 +11,10 @@ //! slot. When all associated `WeakRef` values are dropped, the //! `WeakBox` itself is dropped too. -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::trace::JSTraceable; +use dom::bindings::cell::DomRefCell; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::DomRoot; +use dom::bindings::trace::JSTraceable; use js::glue::JS_GetReservedSlot; use js::jsapi::{JSTracer, JS_SetReservedSlot}; use js::jsval::PrivateValue; @@ -269,7 +269,7 @@ impl DerefMut for WeakRefVec { /// An entry of a vector of weak references. Passed to the closure /// given to `WeakRefVec::update`. #[allow_unrooted_interior] -pub struct WeakRefEntry<'a, T: WeakReferenceable> { +pub struct WeakRefEntry<'a, T: WeakReferenceable + 'a> { vec: &'a mut WeakRefVec, index: &'a mut usize, } diff --git a/components/script/dom/bindings/xmlname.rs b/components/script/dom/bindings/xmlname.rs index 028b23bb9874..2a2b8a462a0d 100644 --- a/components/script/dom/bindings/xmlname.rs +++ b/components/script/dom/bindings/xmlname.rs @@ -4,9 +4,9 @@ //! Functions for validating and extracting qualified XML names. -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::str::DOMString; -use html5ever::{LocalName, Namespace, Prefix}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::str::DOMString; +use html5ever::{Prefix, LocalName, Namespace}; /// Validate a qualified name. See https://dom.spec.whatwg.org/#validate for details. pub fn validate_qualified_name(qualified_name: &str) -> ErrorResult { diff --git a/components/script/dom/biquadfilternode.rs b/components/script/dom/biquadfilternode.rs index 15f5f09e07a0..2ee309498be0 100644 --- a/components/script/dom/biquadfilternode.rs +++ b/components/script/dom/biquadfilternode.rs @@ -2,25 +2,21 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::AudioNode; -use crate::dom::audioparam::AudioParam; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterOptions; -use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterType; -use crate::dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::{ - self, BiquadFilterNodeMethods, -}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::window::Window; +use dom::audionode::AudioNode; +use dom::audioparam::AudioParam; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; +use dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::{self, BiquadFilterNodeMethods}; +use dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterOptions; +use dom::bindings::codegen::Bindings::BiquadFilterNodeBinding::BiquadFilterType; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot}; +use dom::window::Window; use dom_struct::dom_struct; -use servo_media::audio::biquad_filter_node::BiquadFilterNodeMessage; use servo_media::audio::biquad_filter_node::{BiquadFilterNodeOptions, FilterType}; +use servo_media::audio::biquad_filter_node::BiquadFilterNodeMessage; use servo_media::audio::node::{AudioNodeInit, AudioNodeMessage}; use servo_media::audio::param::ParamType; use std::cell::Cell; @@ -43,10 +39,9 @@ impl BiquadFilterNode { context: &BaseAudioContext, options: &BiquadFilterOptions, ) -> Fallible { - let node_options = - options - .parent - .unwrap_or(2, ChannelCountMode::Max, ChannelInterpretation::Speakers); + let node_options = options.parent + .unwrap_or(2, ChannelCountMode::Max, + ChannelInterpretation::Speakers); let filter = Cell::new(options.type_); let options = options.into(); let node = AudioNode::new_inherited( @@ -62,9 +57,9 @@ impl BiquadFilterNode { node.node_id(), ParamType::Gain, AutomationRate::A_rate, - options.gain, // default value - f32::MIN, // min value - f32::MAX, // max value + options.gain, // default value + f32::MIN, // min value + f32::MAX, // max value ); let q = AudioParam::new( window, @@ -72,9 +67,9 @@ impl BiquadFilterNode { node.node_id(), ParamType::Q, AutomationRate::A_rate, - options.q, // default value - f32::MIN, // min value - f32::MAX, // max value + options.q, // default value + f32::MIN, // min value + f32::MAX, // max value ); let frequency = AudioParam::new( window, @@ -82,9 +77,9 @@ impl BiquadFilterNode { node.node_id(), ParamType::Frequency, AutomationRate::A_rate, - options.frequency, // default value - f32::MIN, // min value - f32::MAX, // max value + options.frequency, // default value + f32::MIN, // min value + f32::MAX, // max value ); let detune = AudioParam::new( window, @@ -92,9 +87,9 @@ impl BiquadFilterNode { node.node_id(), ParamType::Detune, AutomationRate::A_rate, - options.detune, // default value - f32::MIN, // min value - f32::MAX, // max value + options.detune, // default value + f32::MIN, // min value + f32::MAX, // max value ); Ok(BiquadFilterNode { node, @@ -113,11 +108,7 @@ impl BiquadFilterNode { options: &BiquadFilterOptions, ) -> Fallible> { let node = BiquadFilterNode::new_inherited(window, context, options)?; - Ok(reflect_dom_object( - Box::new(node), - window, - BiquadFilterNodeBinding::Wrap, - )) + Ok(reflect_dom_object(Box::new(node), window, BiquadFilterNodeBinding::Wrap)) } pub fn Constructor( @@ -158,9 +149,10 @@ impl BiquadFilterNodeMethods for BiquadFilterNode { // https://webaudio.github.io/web-audio-api/#dom-biquadfilternode-type fn SetType(&self, filter: BiquadFilterType) { self.filter.set(filter); - self.node.message(AudioNodeMessage::BiquadFilterNode( - BiquadFilterNodeMessage::SetFilterType(filter.into()), - )); + self.node + .message(AudioNodeMessage::BiquadFilterNode( + BiquadFilterNodeMessage::SetFilterType(filter.into()), + )); } } @@ -171,7 +163,7 @@ impl<'a> From<&'a BiquadFilterOptions> for BiquadFilterNodeOptions { q: *options.Q, frequency: *options.frequency, detune: *options.detune, - filter: options.type_.into(), + filter: options.type_.into() } } } diff --git a/components/script/dom/blob.rs b/components/script/dom/blob.rs index 4842f6b29fa6..490404bbf32d 100644 --- a/components/script/dom/blob.rs +++ b/components/script/dom/blob.rs @@ -2,19 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BlobBinding; -use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; -use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BlobBinding; +use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; +use dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use net_traits::blob_url_store::{get_blob_origin, BlobBuf}; -use net_traits::filemanager_thread::{FileManagerThreadMsg, ReadFileProgress, RelativePos}; use net_traits::{CoreResourceMsg, IpcSend}; +use net_traits::blob_url_store::{BlobBuf, get_blob_origin}; +use net_traits::filemanager_thread::{FileManagerThreadMsg, ReadFileProgress, RelativePos}; use profile_traits::ipc; use std::mem; use std::ops::Index; diff --git a/components/script/dom/bluetooth.rs b/components/script/dom/bluetooth.rs index c5985ac0964d..99c02576a1b9 100644 --- a/components/script/dom/bluetooth.rs +++ b/components/script/dom/bluetooth.rs @@ -7,29 +7,27 @@ use bluetooth_traits::{BluetoothResponse, BluetoothResponseResult}; use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; use bluetooth_traits::scanfilter::{BluetoothScanfilter, BluetoothScanfilterSequence}; use bluetooth_traits::scanfilter::{RequestDeviceoptions, ServiceUUIDSequence}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothDataFilterInit}; -use crate::dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions}; -use crate::dom::bindings::codegen::Bindings::BluetoothBinding::BluetoothLEScanFilterInit; -use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerBinding:: +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BluetoothBinding::{self, BluetoothDataFilterInit, BluetoothLEScanFilterInit}; +use dom::bindings::codegen::Bindings::BluetoothBinding::{BluetoothMethods, RequestDeviceOptions}; +use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::BluetoothPermissionDescriptor; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerBinding:: BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; -use crate::dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong}; -use crate::dom::bindings::error::Error::{self, Network, Security, Type}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{DomObject, reflect_dom_object}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bluetoothdevice::BluetoothDevice; -use crate::dom::bluetoothpermissionresult::BluetoothPermissionResult; -use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::permissions::{get_descriptor_permission_state, PermissionAlgorithm}; -use crate::dom::promise::Promise; -use crate::task::TaskOnce; +use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; +use dom::bindings::codegen::UnionTypes::{ArrayBufferViewOrArrayBuffer, StringOrUnsignedLong}; +use dom::bindings::error::Error::{self, Network, Security, Type}; +use dom::bindings::error::Fallible; +use dom::bindings::refcounted::{Trusted, TrustedPromise}; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::bluetoothdevice::BluetoothDevice; +use dom::bluetoothpermissionresult::BluetoothPermissionResult; +use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID, UUID}; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::permissions::{get_descriptor_permission_state, PermissionAlgorithm}; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcSender}; use ipc_channel::router::ROUTER; @@ -42,6 +40,7 @@ use std::collections::HashMap; use std::rc::Rc; use std::str::FromStr; use std::sync::{Arc, Mutex}; +use task::TaskOnce; const KEY_CONVERSION_ERROR: &'static str = "This `manufacturerData` key can not be parsed as unsigned short:"; @@ -334,8 +333,7 @@ where single, child_type, sender, - )) - .unwrap(); + )).unwrap(); return p; } @@ -695,8 +693,7 @@ impl PermissionAlgorithm for Bluetooth { device_id.clone(), BluetoothScanfilterSequence::new(scan_filters), sender, - )) - .unwrap(); + )).unwrap(); match receiver.recv().unwrap() { Ok(true) => (), diff --git a/components/script/dom/bluetoothadvertisingevent.rs b/components/script/dom/bluetoothadvertisingevent.rs index 0ed93ce4ae85..2dffb0a4dfce 100644 --- a/components/script/dom/bluetoothadvertisingevent.rs +++ b/components/script/dom/bluetoothadvertisingevent.rs @@ -2,20 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::BluetoothAdvertisingEventMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::{ - self, BluetoothAdvertisingEventInit, -}; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{Dom, DomRoot, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bluetoothdevice::BluetoothDevice; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::{self, BluetoothAdvertisingEventInit}; +use dom::bindings::codegen::Bindings::BluetoothAdvertisingEventBinding::BluetoothAdvertisingEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot, RootedReference}; +use dom::bindings::str::DOMString; +use dom::bluetoothdevice::BluetoothDevice; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/bluetoothcharacteristicproperties.rs b/components/script/dom/bluetoothcharacteristicproperties.rs index 05aee3196139..900ec257c7d5 100644 --- a/components/script/dom/bluetoothcharacteristicproperties.rs +++ b/components/script/dom/bluetoothcharacteristicproperties.rs @@ -2,11 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::BluetoothCharacteristicPropertiesMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding; +use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: +BluetoothCharacteristicPropertiesMethods; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://webbluetoothcg.github.io/web-bluetooth/#characteristicproperties diff --git a/components/script/dom/bluetoothdevice.rs b/components/script/dom/bluetoothdevice.rs index 0810dff64132..ae97626b60e1 100644 --- a/components/script/dom/bluetoothdevice.rs +++ b/components/script/dom/bluetoothdevice.rs @@ -4,25 +4,25 @@ use bluetooth_traits::{BluetoothCharacteristicMsg, BluetoothDescriptorMsg}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse, BluetoothServiceMsg}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothDeviceBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{response_async, AsyncBluetoothListener, Bluetooth}; -use crate::dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; -use crate::dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic; -use crate::dom::bluetoothremotegattdescriptor::BluetoothRemoteGATTDescriptor; -use crate::dom::bluetoothremotegattserver::BluetoothRemoteGATTServer; -use crate::dom::bluetoothremotegattservice::BluetoothRemoteGATTService; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BluetoothDeviceBinding; +use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; +use dom::bindings::error::Error; +use dom::bindings::error::ErrorResult; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, response_async}; +use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; +use dom::bluetoothremotegattcharacteristic::BluetoothRemoteGATTCharacteristic; +use dom::bluetoothremotegattdescriptor::BluetoothRemoteGATTDescriptor; +use dom::bluetoothremotegattserver::BluetoothRemoteGATTServer; +use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use profile_traits::ipc; @@ -152,8 +152,7 @@ impl BluetoothDevice { .send(BluetoothRequest::IsRepresentedDeviceNull( self.Id().to_string(), sender, - )) - .unwrap(); + )).unwrap(); receiver.recv().unwrap() } @@ -243,8 +242,7 @@ impl BluetoothDevice { .send(BluetoothRequest::GATTServerDisconnect( String::from(self.Id()), sender, - )) - .unwrap(); + )).unwrap(); receiver.recv().unwrap().map_err(Error::from) } } @@ -288,8 +286,7 @@ impl BluetoothDeviceMethods for BluetoothDevice { .send(BluetoothRequest::WatchAdvertisements( String::from(self.Id()), sender, - )) - .unwrap(); + )).unwrap(); return p; } diff --git a/components/script/dom/bluetoothpermissionresult.rs b/components/script/dom/bluetoothpermissionresult.rs index 3aa9d9a19b85..a9208ed8cb20 100644 --- a/components/script/dom/bluetoothpermissionresult.rs +++ b/components/script/dom/bluetoothpermissionresult.rs @@ -3,25 +3,21 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{ - self, BluetoothPermissionResultMethods, -}; -use crate::dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorBinding::NavigatorMethods; -use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusBinding::PermissionStatusMethods; -use crate::dom::bindings::codegen::Bindings::PermissionStatusBinding::{ - PermissionName, PermissionState, -}; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{AllowedBluetoothDevice, AsyncBluetoothListener, Bluetooth}; -use crate::dom::bluetoothdevice::BluetoothDevice; -use crate::dom::globalscope::GlobalScope; -use crate::dom::permissionstatus::PermissionStatus; -use crate::dom::promise::Promise; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BluetoothPermissionResultBinding::{self, BluetoothPermissionResultMethods}; +use dom::bindings::codegen::Bindings::NavigatorBinding::NavigatorBinding::NavigatorMethods; +use dom::bindings::codegen::Bindings::PermissionStatusBinding::{PermissionName, PermissionState}; +use dom::bindings::codegen::Bindings::PermissionStatusBinding::PermissionStatusBinding::PermissionStatusMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::error::Error; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::bluetooth::{AsyncBluetoothListener, Bluetooth, AllowedBluetoothDevice}; +use dom::bluetoothdevice::BluetoothDevice; +use dom::globalscope::GlobalScope; +use dom::permissionstatus::PermissionStatus; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use std::rc::Rc; diff --git a/components/script/dom/bluetoothremotegattcharacteristic.rs b/components/script/dom/bluetoothremotegattcharacteristic.rs index 41732f120f9b..70cbf23ffd23 100644 --- a/components/script/dom/bluetoothremotegattcharacteristic.rs +++ b/components/script/dom/bluetoothremotegattcharacteristic.rs @@ -2,29 +2,29 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding::BluetoothCharacteristicPropertiesMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding::BluetoothRemoteGATTCharacteristicMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; -use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; -use crate::dom::bindings::error::Error::{ - self, InvalidModification, Network, NotSupported, Security, -}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::{ByteString, DOMString}; -use crate::dom::bluetooth::{get_gatt_children, response_async, AsyncBluetoothListener}; -use crate::dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; -use crate::dom::bluetoothremotegattservice::BluetoothRemoteGATTService; -use crate::dom::bluetoothuuid::{BluetoothDescriptorUUID, BluetoothUUID}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BluetoothCharacteristicPropertiesBinding:: +BluetoothCharacteristicPropertiesMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: +BluetoothRemoteGATTCharacteristicMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; +use dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; +use dom::bindings::error::Error::{self, InvalidModification, Network, NotSupported, Security}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::{ByteString, DOMString}; +use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; +use dom::bluetoothcharacteristicproperties::BluetoothCharacteristicProperties; +use dom::bluetoothremotegattservice::BluetoothRemoteGATTService; +use dom::bluetoothuuid::{BluetoothDescriptorUUID, BluetoothUUID}; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use std::rc::Rc; @@ -216,8 +216,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris self.get_instance_id(), vec, sender, - )) - .unwrap(); + )).unwrap(); return p; } @@ -254,8 +253,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris self.get_instance_id(), true, sender, - )) - .unwrap(); + )).unwrap(); return p; } @@ -274,8 +272,7 @@ impl BluetoothRemoteGATTCharacteristicMethods for BluetoothRemoteGATTCharacteris self.get_instance_id(), false, sender, - )) - .unwrap(); + )).unwrap(); return p; } diff --git a/components/script/dom/bluetoothremotegattdescriptor.rs b/components/script/dom/bluetoothremotegattdescriptor.rs index 76a113c96e37..b0eb6476fe32 100644 --- a/components/script/dom/bluetoothremotegattdescriptor.rs +++ b/components/script/dom/bluetoothremotegattdescriptor.rs @@ -2,25 +2,24 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use bluetooth_traits::blocklist::{uuid_is_blocklisted, Blocklist}; use bluetooth_traits::{BluetoothRequest, BluetoothResponse}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding::BluetoothRemoteGATTCharacteristicMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding::BluetoothRemoteGATTDescriptorMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; -use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; -use crate::dom::bindings::error::Error::{self, InvalidModification, Network, Security}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::{ByteString, DOMString}; -use crate::dom::bluetooth::{response_async, AsyncBluetoothListener}; -use crate::dom::bluetoothremotegattcharacteristic::{ - BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH, -}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use bluetooth_traits::blocklist::{Blocklist, uuid_is_blocklisted}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTCharacteristicBinding:: +BluetoothRemoteGATTCharacteristicMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTDescriptorBinding::BluetoothRemoteGATTDescriptorMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; +use dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer; +use dom::bindings::error::Error::{self, InvalidModification, Network, Security}; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::{ByteString, DOMString}; +use dom::bluetooth::{AsyncBluetoothListener, response_async}; +use dom::bluetoothremotegattcharacteristic::{BluetoothRemoteGATTCharacteristic, MAXIMUM_ATTRIBUTE_LENGTH}; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use std::rc::Rc; @@ -167,8 +166,7 @@ impl BluetoothRemoteGATTDescriptorMethods for BluetoothRemoteGATTDescriptor { self.get_instance_id(), vec, sender, - )) - .unwrap(); + )).unwrap(); return p; } } diff --git a/components/script/dom/bluetoothremotegattserver.rs b/components/script/dom/bluetoothremotegattserver.rs index dff68c60eca3..3d4e5125b3e2 100644 --- a/components/script/dom/bluetoothremotegattserver.rs +++ b/components/script/dom/bluetoothremotegattserver.rs @@ -3,18 +3,18 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use bluetooth_traits::{BluetoothRequest, BluetoothResponse, GATTType}; -use crate::dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bluetooth::{get_gatt_children, response_async, AsyncBluetoothListener}; -use crate::dom::bluetoothdevice::BluetoothDevice; -use crate::dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use dom::bindings::codegen::Bindings::BluetoothDeviceBinding::BluetoothDeviceMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; +use dom::bindings::error::Error; +use dom::bindings::error::ErrorResult; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children, response_async}; +use dom::bluetoothdevice::BluetoothDevice; +use dom::bluetoothuuid::{BluetoothServiceUUID, BluetoothUUID}; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; use std::cell::Cell; @@ -87,8 +87,7 @@ impl BluetoothRemoteGATTServerMethods for BluetoothRemoteGATTServer { .send(BluetoothRequest::GATTServerConnect( String::from(self.Device().Id()), sender, - )) - .unwrap(); + )).unwrap(); // Step 5: return promise. return p; } diff --git a/components/script/dom/bluetoothremotegattservice.rs b/components/script/dom/bluetoothremotegattservice.rs index 1aeaf6216915..85aa40c874cc 100644 --- a/components/script/dom/bluetoothremotegattservice.rs +++ b/components/script/dom/bluetoothremotegattservice.rs @@ -3,19 +3,19 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use bluetooth_traits::{BluetoothResponse, GATTType}; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding; -use crate::dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; -use crate::dom::bindings::error::Error; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bluetooth::{get_gatt_children, AsyncBluetoothListener}; -use crate::dom::bluetoothdevice::BluetoothDevice; -use crate::dom::bluetoothuuid::{BluetoothCharacteristicUUID, BluetoothServiceUUID, BluetoothUUID}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::promise::Promise; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding::BluetoothRemoteGATTServerMethods; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding; +use dom::bindings::codegen::Bindings::BluetoothRemoteGATTServiceBinding::BluetoothRemoteGATTServiceMethods; +use dom::bindings::error::Error; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::bluetooth::{AsyncBluetoothListener, get_gatt_children}; +use dom::bluetoothdevice::BluetoothDevice; +use dom::bluetoothuuid::{BluetoothCharacteristicUUID, BluetoothServiceUUID, BluetoothUUID}; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::promise::Promise; use dom_struct::dom_struct; use std::rc::Rc; diff --git a/components/script/dom/bluetoothuuid.rs b/components/script/dom/bluetoothuuid.rs index 05b21ab16330..212318650c71 100644 --- a/components/script/dom/bluetoothuuid.rs +++ b/components/script/dom/bluetoothuuid.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::UnionTypes::StringOrUnsignedLong; -use crate::dom::bindings::error::Error::Type; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::Reflector; -use crate::dom::bindings::str::DOMString; -use crate::dom::window::Window; +use dom::bindings::codegen::UnionTypes::StringOrUnsignedLong; +use dom::bindings::error::Error::Type; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::Reflector; +use dom::bindings::str::DOMString; +use dom::window::Window; use dom_struct::dom_struct; use regex::Regex; diff --git a/components/script/dom/canvasgradient.rs b/components/script/dom/canvasgradient.rs index 1ff600937eb9..e3f4ea54f4bc 100644 --- a/components/script/dom/canvasgradient.rs +++ b/components/script/dom/canvasgradient.rs @@ -2,20 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use canvas_traits::canvas::{ - CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle, -}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CanvasGradientBinding; -use crate::dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; -use crate::dom::bindings::error::{Error, ErrorResult}; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::globalscope::GlobalScope; -use cssparser::Color as CSSColor; +use canvas_traits::canvas::{CanvasGradientStop, FillOrStrokeStyle, LinearGradientStyle, RadialGradientStyle}; use cssparser::{Parser, ParserInput, RGBA}; +use cssparser::Color as CSSColor; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CanvasGradientBinding; +use dom::bindings::codegen::Bindings::CanvasGradientBinding::CanvasGradientMethods; +use dom::bindings::error::{Error, ErrorResult}; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://html.spec.whatwg.org/multipage/#canvasgradient diff --git a/components/script/dom/canvaspattern.rs b/components/script/dom/canvaspattern.rs index d5d18e4fa8b5..ced7a6bb11be 100644 --- a/components/script/dom/canvaspattern.rs +++ b/components/script/dom/canvaspattern.rs @@ -3,11 +3,11 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use canvas_traits::canvas::{FillOrStrokeStyle, RepetitionStyle, SurfaceStyle}; -use crate::dom::bindings::codegen::Bindings::CanvasPatternBinding; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::canvasgradient::ToFillOrStrokeStyle; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::CanvasPatternBinding; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::canvasgradient::ToFillOrStrokeStyle; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Size2D; @@ -16,7 +16,7 @@ use euclid::Size2D; pub struct CanvasPattern { reflector_: Reflector, surface_data: Vec, - surface_size: Size2D, + surface_size: Size2D, repeat_x: bool, repeat_y: bool, origin_clean: bool, @@ -25,7 +25,7 @@ pub struct CanvasPattern { impl CanvasPattern { fn new_inherited( surface_data: Vec, - surface_size: Size2D, + surface_size: Size2D, repeat: RepetitionStyle, origin_clean: bool, ) -> CanvasPattern { @@ -39,7 +39,7 @@ impl CanvasPattern { CanvasPattern { reflector_: Reflector::new(), surface_data: surface_data, - surface_size, + surface_size: surface_size, repeat_x: x, repeat_y: y, origin_clean: origin_clean, @@ -48,7 +48,7 @@ impl CanvasPattern { pub fn new( global: &GlobalScope, surface_data: Vec, - surface_size: Size2D, + surface_size: Size2D, repeat: RepetitionStyle, origin_clean: bool, ) -> DomRoot { diff --git a/components/script/dom/canvasrenderingcontext2d.rs b/components/script/dom/canvasrenderingcontext2d.rs index 3a031095dc8a..e3ca01c311e0 100644 --- a/components/script/dom/canvasrenderingcontext2d.rs +++ b/components/script/dom/canvasrenderingcontext2d.rs @@ -2,37 +2,36 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use canvas_traits::canvas::{Canvas2dMsg, CanvasId, CanvasMsg}; +use canvas_traits::canvas::{Canvas2dMsg, CanvasMsg, CanvasId}; use canvas_traits::canvas::{CompositionOrBlending, FillOrStrokeStyle, FillRule}; use canvas_traits::canvas::{LineCapStyle, LineJoinStyle, LinearGradientStyle}; -use canvas_traits::canvas::{RadialGradientStyle, RepetitionStyle}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasFillRule; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasImageSource; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasLineCap; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasLineJoin; -use crate::dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; -use crate::dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; -use crate::dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; -use crate::dom::canvaspattern::CanvasPattern; -use crate::dom::element::Element; -use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlcanvaselement::{CanvasContext, HTMLCanvasElement}; -use crate::dom::imagedata::ImageData; -use crate::dom::node::{window_from_node, Node, NodeDamage}; -use crate::unpremultiplytable::UNPREMULTIPLY_TABLE; -use cssparser::Color as CSSColor; +use canvas_traits::canvas::{RadialGradientStyle, RepetitionStyle, byte_swap_and_premultiply}; use cssparser::{Parser, ParserInput, RGBA}; +use cssparser::Color as CSSColor; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasFillRule; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasImageSource; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasLineCap; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasLineJoin; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; +use dom::bindings::codegen::Bindings::ImageDataBinding::ImageDataMethods; +use dom::bindings::codegen::UnionTypes::StringOrCanvasGradientOrCanvasPattern; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, LayoutDom}; +use dom::bindings::str::DOMString; +use dom::canvasgradient::{CanvasGradient, CanvasGradientStyle, ToFillOrStrokeStyle}; +use dom::canvaspattern::CanvasPattern; +use dom::element::Element; +use dom::globalscope::GlobalScope; +use dom::htmlcanvaselement::{CanvasContext, HTMLCanvasElement}; +use dom::imagedata::ImageData; +use dom::node::{Node, NodeDamage, window_from_node}; use dom_struct::dom_struct; -use euclid::{vec2, Point2D, Rect, Size2D, Transform2D}; +use euclid::{Transform2D, Point2D, Vector2D, Rect, Size2D, vec2}; use ipc_channel::ipc::{self, IpcSender}; use net_traits::image::base::PixelFormat; use net_traits::image_cache::CanRequestImages; @@ -41,13 +40,15 @@ use net_traits::image_cache::ImageOrMetadataAvailable; use net_traits::image_cache::ImageResponse; use net_traits::image_cache::ImageState; use net_traits::image_cache::UsePlaceholder; +use num_traits::ToPrimitive; use profile_traits::ipc as profiled_ipc; use script_traits::ScriptMsg; use servo_url::ServoUrl; +use std::{cmp, fmt, mem}; use std::cell::Cell; use std::str::FromStr; use std::sync::Arc; -use std::{fmt, mem}; +use unpremultiplytable::UNPREMULTIPLY_TABLE; #[must_root] #[derive(Clone, JSTraceable, MallocSizeOf)] @@ -125,9 +126,9 @@ impl CanvasRenderingContext2D { pub fn new_inherited( global: &GlobalScope, canvas: Option<&HTMLCanvasElement>, - image_cache: Arc, + image_cache: Arc, base_url: ServoUrl, - size: Size2D, + size: Size2D, ) -> CanvasRenderingContext2D { debug!("Creating new canvas rendering context."); let (sender, receiver) = @@ -156,7 +157,7 @@ impl CanvasRenderingContext2D { pub fn new( global: &GlobalScope, canvas: &HTMLCanvasElement, - size: Size2D, + size: Size2D, ) -> DomRoot { let window = window_from_node(canvas); let image_cache = window.image_cache(); @@ -172,7 +173,7 @@ impl CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#concept-canvas-set-bitmap-dimensions - pub fn set_bitmap_dimensions(&self, size: Size2D) { + pub fn set_bitmap_dimensions(&self, size: Size2D) { self.reset_to_initial_state(); self.ipc_renderer .send(CanvasMsg::Recreate(size, self.get_canvas_id())) @@ -265,7 +266,7 @@ impl CanvasRenderingContext2D { CanvasImageSource::HTMLCanvasElement(canvas) => canvas.origin_is_clean(), CanvasImageSource::HTMLImageElement(image) => { image.same_origin(GlobalScope::entry().origin()) - }, + } CanvasImageSource::CSSStyleValue(_) => true, } } @@ -402,15 +403,39 @@ impl CanvasRenderingContext2D { dh: Option, ) -> ErrorResult { debug!("Fetching image {}.", url); - let (mut image_data, image_size) = self.fetch_image_data(url).ok_or(Error::InvalidState)?; - pixels::premultiply_inplace(&mut image_data); - let image_size = image_size.to_f64(); - + // https://html.spec.whatwg.org/multipage/#img-error + // If the image argument is an HTMLImageElement object that is in the broken state, + // then throw an InvalidStateError exception + let (image_data, image_size) = match self.fetch_image_data(url) { + Some((mut data, size)) => { + // Pixels come from cache in BGRA order and drawImage expects RGBA so we + // have to swap the color values + byte_swap_and_premultiply(&mut data); + let size = Size2D::new(size.width as f64, size.height as f64); + (data, size) + }, + None => return Err(Error::InvalidState), + }; let dw = dw.unwrap_or(image_size.width); let dh = dh.unwrap_or(image_size.height); let sw = sw.unwrap_or(image_size.width); let sh = sh.unwrap_or(image_size.height); + self.draw_image_data(image_data, image_size, sx, sy, sw, sh, dx, dy, dw, dh) + } + fn draw_image_data( + &self, + image_data: Vec, + image_size: Size2D, + sx: f64, + sy: f64, + sw: f64, + sh: f64, + dx: f64, + dy: f64, + dw: f64, + dh: f64, + ) -> ErrorResult { // Establish the source and destination rectangles let (source_rect, dest_rect) = self.adjust_source_dest_rects(image_size, sx, sy, sw, sh, dx, dy, dw, dh); @@ -431,7 +456,7 @@ impl CanvasRenderingContext2D { Ok(()) } - fn fetch_image_data(&self, url: ServoUrl) -> Option<(Vec, Size2D)> { + fn fetch_image_data(&self, url: ServoUrl) -> Option<(Vec, Size2D)> { let img = match self.request_image_from_cache(url) { ImageResponse::Loaded(img, _) => img, ImageResponse::PlaceholderLoaded(_, _) | @@ -441,7 +466,7 @@ impl CanvasRenderingContext2D { }, }; - let image_size = Size2D::new(img.width, img.height); + let image_size = Size2D::new(img.width as i32, img.height as i32); let image_data = match img.format { PixelFormat::BGRA8 => img.bytes.to_vec(), PixelFormat::K8 => panic!("K8 color type not supported"), @@ -550,31 +575,6 @@ impl CanvasRenderingContext2D { fn set_origin_unclean(&self) { self.origin_clean.set(false) } - - pub fn get_rect(&self, rect: Rect) -> Vec { - assert!(self.origin_is_clean()); - - // FIXME(nox): This is probably wrong when this is a context for an - // offscreen canvas. - let canvas_size = self - .canvas - .as_ref() - .map_or(Size2D::zero(), |c| c.get_size()); - assert!(Rect::from_size(canvas_size).contains_rect(&rect)); - - let (sender, receiver) = ipc::bytes_channel().unwrap(); - self.send_canvas_2d_msg(Canvas2dMsg::GetImageData(rect, canvas_size, sender)); - let mut pixels = receiver.recv().unwrap().to_vec(); - - for chunk in pixels.chunks_mut(4) { - let b = chunk[0]; - chunk[0] = UNPREMULTIPLY_TABLE[256 * (chunk[3] as usize) + chunk[2] as usize]; - chunk[1] = UNPREMULTIPLY_TABLE[256 * (chunk[3] as usize) + chunk[1] as usize]; - chunk[2] = UNPREMULTIPLY_TABLE[256 * (chunk[3] as usize) + b as usize]; - } - - pixels - } } pub trait LayoutCanvasRenderingContext2DHelpers { @@ -1117,11 +1117,14 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata - fn CreateImageData(&self, sw: i32, sh: i32) -> Fallible> { - if sw == 0 || sh == 0 { + fn CreateImageData(&self, sw: Finite, sh: Finite) -> Fallible> { + if *sw == 0.0 || *sh == 0.0 { return Err(Error::IndexSize); } - ImageData::new(&self.global(), sw.abs() as u32, sh.abs() as u32, None) + + let sw = cmp::max(1, sw.abs().to_u32().unwrap()); + let sh = cmp::max(1, sh.abs().to_u32().unwrap()); + ImageData::new(&self.global(), sw, sh, None) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-createimagedata @@ -1130,112 +1133,101 @@ impl CanvasRenderingContext2DMethods for CanvasRenderingContext2D { } // https://html.spec.whatwg.org/multipage/#dom-context-2d-getimagedata - fn GetImageData(&self, sx: i32, sy: i32, sw: i32, sh: i32) -> Fallible> { - // FIXME(nox): There are many arithmetic operations here that can - // overflow or underflow, this should probably be audited. + fn GetImageData( + &self, + sx: Finite, + sy: Finite, + sw: Finite, + sh: Finite, + ) -> Fallible> { + if !self.origin_is_clean() { + return Err(Error::Security); + } - if sw == 0 || sh == 0 { + let mut sx = *sx; + let mut sy = *sy; + let mut sw = *sw; + let mut sh = *sh; + + if sw == 0.0 || sh == 0.0 { return Err(Error::IndexSize); } - if !self.origin_is_clean() { - return Err(Error::Security); + if sw < 0.0 { + sw = -sw; + sx -= sw; } + if sh < 0.0 { + sh = -sh; + sy -= sh; + } + + let sh = cmp::max(1, sh.to_u32().unwrap()); + let sw = cmp::max(1, sw.to_u32().unwrap()); - let (origin, size) = adjust_size_sign(Point2D::new(sx, sy), Size2D::new(sw, sh)); - // FIXME(nox): This is probably wrong when this is a context for an - // offscreen canvas. + let (sender, receiver) = ipc::bytes_channel().unwrap(); + let dest_rect = Rect::new( + Point2D::new(sx.to_i32().unwrap(), sy.to_i32().unwrap()), + Size2D::new(sw as i32, sh as i32), + ); let canvas_size = self .canvas .as_ref() - .map_or(Size2D::zero(), |c| c.get_size()); - let read_rect = match pixels::clip(origin, size, canvas_size) { - Some(rect) => rect, - None => { - // All the pixels are outside the canvas surface. - return ImageData::new(&self.global(), size.width, size.height, None); - }, - }; + .map(|c| c.get_size()) + .unwrap_or(Size2D::zero()); + let canvas_size = Size2D::new(canvas_size.width as f64, canvas_size.height as f64); + self.send_canvas_2d_msg(Canvas2dMsg::GetImageData(dest_rect, canvas_size, sender)); + let mut data = receiver.recv().unwrap(); + + // Byte swap and unmultiply alpha. + for chunk in data.chunks_mut(4) { + let (b, g, r, a) = (chunk[0], chunk[1], chunk[2], chunk[3]); + chunk[0] = UNPREMULTIPLY_TABLE[256 * (a as usize) + r as usize]; + chunk[1] = UNPREMULTIPLY_TABLE[256 * (a as usize) + g as usize]; + chunk[2] = UNPREMULTIPLY_TABLE[256 * (a as usize) + b as usize]; + } - ImageData::new( - &self.global(), - size.width, - size.height, - Some(self.get_rect(read_rect)), - ) + ImageData::new(&self.global(), sw, sh, Some(data.to_vec())) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata - fn PutImageData(&self, imagedata: &ImageData, dx: i32, dy: i32) { + fn PutImageData(&self, imagedata: &ImageData, dx: Finite, dy: Finite) { self.PutImageData_( imagedata, dx, dy, - 0, - 0, - imagedata.Width() as i32, - imagedata.Height() as i32, + Finite::wrap(0f64), + Finite::wrap(0f64), + Finite::wrap(imagedata.Width() as f64), + Finite::wrap(imagedata.Height() as f64), ) } // https://html.spec.whatwg.org/multipage/#dom-context-2d-putimagedata - #[allow(unsafe_code)] fn PutImageData_( &self, imagedata: &ImageData, - dx: i32, - dy: i32, - dirty_x: i32, - dirty_y: i32, - dirty_width: i32, - dirty_height: i32, + dx: Finite, + dy: Finite, + dirty_x: Finite, + dirty_y: Finite, + dirty_width: Finite, + dirty_height: Finite, ) { - // FIXME(nox): There are many arithmetic operations here that can - // overflow or underflow, this should probably be audited. - - let imagedata_size = Size2D::new(imagedata.Width(), imagedata.Height()); - if imagedata_size.area() == 0 { - return; - } + let data = imagedata.get_data_array(); + let offset = Vector2D::new(*dx, *dy); + let image_data_size = Size2D::new(imagedata.Width() as f64, imagedata.Height() as f64); - // Step 1. - // Done later. - - // Step 2. - // TODO: throw InvalidState if buffer is detached. - - // FIXME(nox): This is probably wrong when this is a context for an - // offscreen canvas. - let canvas_size = self - .canvas - .as_ref() - .map_or(Size2D::zero(), |c| c.get_size()); - - // Steps 3-6. - let (src_origin, src_size) = adjust_size_sign( - Point2D::new(dirty_x, dirty_y), - Size2D::new(dirty_width, dirty_height), - ); - let src_rect = match pixels::clip(src_origin, src_size, imagedata_size) { - Some(rect) => rect, - None => return, - }; - let (dst_origin, _) = adjust_size_sign( - Point2D::new(dirty_x.saturating_add(dx), dirty_y.saturating_add(dy)), - Size2D::new(dirty_width, dirty_height), + let dirty_rect = Rect::new( + Point2D::new(*dirty_x, *dirty_y), + Size2D::new(*dirty_width, *dirty_height), ); - // By clipping to the canvas surface, we avoid sending any pixel - // that would fall outside it. - let dst_rect = match pixels::clip(dst_origin, src_rect.size, canvas_size) { - Some(rect) => rect, - None => return, - }; - - // Step 7. - let (sender, receiver) = ipc::bytes_channel().unwrap(); - let pixels = unsafe { &imagedata.get_rect(Rect::new(src_rect.origin, dst_rect.size)) }; - self.send_canvas_2d_msg(Canvas2dMsg::PutImageData(dst_rect, receiver)); - sender.send(pixels).unwrap(); + self.send_canvas_2d_msg(Canvas2dMsg::PutImageData( + data.into(), + offset, + image_data_size, + dirty_rect, + )); self.mark_as_dirty(); } @@ -1485,7 +1477,7 @@ fn is_rect_valid(rect: Rect) -> bool { rect.size.width > 0.0 && rect.size.height > 0.0 } -// https://html.spec.whatwg.org/multipage/#serialisation-of-a-color +// https://html.spec.whatwg.org/multipage/#serialisation-of-a-colour fn serialize(color: &RGBA, dest: &mut W) -> fmt::Result where W: fmt::Write, @@ -1516,18 +1508,3 @@ where ) } } - -fn adjust_size_sign( - mut origin: Point2D, - mut size: Size2D, -) -> (Point2D, Size2D) { - if size.width < 0 { - size.width = -size.width; - origin.x = origin.x.saturating_sub(size.width); - } - if size.height < 0 { - size.height = -size.height; - origin.y = origin.y.saturating_sub(size.height); - } - (origin, size.to_u32()) -} diff --git a/components/script/dom/channelmergernode.rs b/components/script/dom/channelmergernode.rs index 88fa3fceaee0..33f009279099 100644 --- a/components/script/dom/channelmergernode.rs +++ b/components/script/dom/channelmergernode.rs @@ -2,18 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::{ - self, ChannelMergerOptions, -}; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::window::Window; +use dom::audionode::{AudioNode, MAX_CHANNEL_COUNT}; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::Bindings::ChannelMergerNodeBinding::{self, ChannelMergerOptions}; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::channel_node::ChannelNodeOptions; use servo_media::audio::node::AudioNodeInit; diff --git a/components/script/dom/characterdata.rs b/components/script/dom/characterdata.rs index 0b614a0f18c1..4b6676ec955d 100644 --- a/components/script/dom/characterdata.rs +++ b/components/script/dom/characterdata.rs @@ -4,24 +4,24 @@ //! DOM bindings for `CharacterData`. -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; -use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; -use crate::dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; -use crate::dom::bindings::codegen::UnionTypes::NodeOrString; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{DomRoot, LayoutDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::comment::Comment; -use crate::dom::document::Document; -use crate::dom::element::Element; -use crate::dom::mutationobserver::{Mutation, MutationObserver}; -use crate::dom::node::{ChildrenMutation, Node, NodeDamage}; -use crate::dom::processinginstruction::ProcessingInstruction; -use crate::dom::text::Text; -use crate::dom::virtualmethods::vtable_for; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CharacterDataBinding::CharacterDataMethods; +use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; +use dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; +use dom::bindings::codegen::InheritTypes::{CharacterDataTypeId, NodeTypeId}; +use dom::bindings::codegen::UnionTypes::NodeOrString; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{DomRoot, LayoutDom}; +use dom::bindings::str::DOMString; +use dom::comment::Comment; +use dom::document::Document; +use dom::element::Element; +use dom::mutationobserver::{Mutation, MutationObserver}; +use dom::node::{ChildrenMutation, Node, NodeDamage}; +use dom::processinginstruction::ProcessingInstruction; +use dom::text::Text; +use dom::virtualmethods::vtable_for; use dom_struct::dom_struct; use servo_config::opts; use std::cell::Ref; diff --git a/components/script/dom/client.rs b/components/script/dom/client.rs index 042976e60ac7..ff63979c4efa 100644 --- a/components/script/dom/client.rs +++ b/components/script/dom/client.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::ClientBinding::FrameType; -use crate::dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::serviceworker::ServiceWorker; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::ClientBinding::{ClientMethods, Wrap}; +use dom::bindings::codegen::Bindings::ClientBinding::FrameType; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::{DOMString, USVString}; +use dom::serviceworker::ServiceWorker; +use dom::window::Window; use dom_struct::dom_struct; use servo_url::ServoUrl; use std::default::Default; diff --git a/components/script/dom/closeevent.rs b/components/script/dom/closeevent.rs index dc8d175deaf3..0c353b681884 100644 --- a/components/script/dom/closeevent.rs +++ b/components/script/dom/closeevent.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CloseEventBinding; -use crate::dom::bindings::codegen::Bindings::CloseEventBinding::CloseEventMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::CloseEventBinding; +use dom::bindings::codegen::Bindings::CloseEventBinding::CloseEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/comment.rs b/components/script/dom/comment.rs index 615e3a4cd2fa..9901a834a413 100644 --- a/components/script/dom/comment.rs +++ b/components/script/dom/comment.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CommentBinding; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::characterdata::CharacterData; -use crate::dom::document::Document; -use crate::dom::node::Node; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CommentBinding; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::Fallible; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::characterdata::CharacterData; +use dom::document::Document; +use dom::node::Node; +use dom::window::Window; use dom_struct::dom_struct; /// An HTML comment. diff --git a/components/script/dom/compositionevent.rs b/components/script/dom/compositionevent.rs index 1ba8a1bf40a4..191572b51abc 100644 --- a/components/script/dom/compositionevent.rs +++ b/components/script/dom/compositionevent.rs @@ -2,16 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CompositionEventBinding::{ - self, CompositionEventMethods, -}; -use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{DomRoot, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::uievent::UIEvent; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CompositionEventBinding::{self, CompositionEventMethods}; +use dom::bindings::codegen::Bindings::UIEventBinding::UIEventBinding::UIEventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{DomRoot, RootedReference}; +use dom::bindings::str::DOMString; +use dom::uievent::UIEvent; +use dom::window::Window; use dom_struct::dom_struct; #[dom_struct] diff --git a/components/script/dom/console.rs b/components/script/dom/console.rs index 18f2d64129e7..410477a79d38 100644 --- a/components/script/dom/console.rs +++ b/components/script/dom/console.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::str::DOMString; -use crate::dom::globalscope::GlobalScope; -use crate::dom::workerglobalscope::WorkerGlobalScope; use devtools_traits::{ConsoleMessage, LogLevel, ScriptToDevtoolsControlMsg}; +use dom::bindings::inheritance::Castable; +use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; +use dom::workerglobalscope::WorkerGlobalScope; use std::io; // https://developer.mozilla.org/en-US/docs/Web/API/Console diff --git a/components/script/dom/create.rs b/components/script/dom/create.rs index 00526a9e59fb..94fe6bd1457b 100644 --- a/components/script/dom/create.rs +++ b/components/script/dom/create.rs @@ -2,85 +2,86 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::error::{report_pending_exception, throw_dom_exception}; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::DomRoot; -use crate::dom::customelementregistry::{is_valid_custom_element_name, upgrade_element}; -use crate::dom::document::Document; -use crate::dom::element::{CustomElementCreationMode, CustomElementState, Element, ElementCreator}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlanchorelement::HTMLAnchorElement; -use crate::dom::htmlareaelement::HTMLAreaElement; -use crate::dom::htmlaudioelement::HTMLAudioElement; -use crate::dom::htmlbaseelement::HTMLBaseElement; -use crate::dom::htmlbodyelement::HTMLBodyElement; -use crate::dom::htmlbrelement::HTMLBRElement; -use crate::dom::htmlbuttonelement::HTMLButtonElement; -use crate::dom::htmlcanvaselement::HTMLCanvasElement; -use crate::dom::htmldataelement::HTMLDataElement; -use crate::dom::htmldatalistelement::HTMLDataListElement; -use crate::dom::htmldetailselement::HTMLDetailsElement; -use crate::dom::htmldialogelement::HTMLDialogElement; -use crate::dom::htmldirectoryelement::HTMLDirectoryElement; -use crate::dom::htmldivelement::HTMLDivElement; -use crate::dom::htmldlistelement::HTMLDListElement; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmlembedelement::HTMLEmbedElement; -use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; -use crate::dom::htmlfontelement::HTMLFontElement; -use crate::dom::htmlformelement::HTMLFormElement; -use crate::dom::htmlframeelement::HTMLFrameElement; -use crate::dom::htmlframesetelement::HTMLFrameSetElement; -use crate::dom::htmlheadelement::HTMLHeadElement; -use crate::dom::htmlheadingelement::HTMLHeadingElement; -use crate::dom::htmlheadingelement::HeadingLevel; -use crate::dom::htmlhrelement::HTMLHRElement; -use crate::dom::htmlhtmlelement::HTMLHtmlElement; -use crate::dom::htmliframeelement::HTMLIFrameElement; -use crate::dom::htmlimageelement::HTMLImageElement; -use crate::dom::htmlinputelement::HTMLInputElement; -use crate::dom::htmllabelelement::HTMLLabelElement; -use crate::dom::htmllegendelement::HTMLLegendElement; -use crate::dom::htmllielement::HTMLLIElement; -use crate::dom::htmllinkelement::HTMLLinkElement; -use crate::dom::htmlmapelement::HTMLMapElement; -use crate::dom::htmlmetaelement::HTMLMetaElement; -use crate::dom::htmlmeterelement::HTMLMeterElement; -use crate::dom::htmlmodelement::HTMLModElement; -use crate::dom::htmlobjectelement::HTMLObjectElement; -use crate::dom::htmlolistelement::HTMLOListElement; -use crate::dom::htmloptgroupelement::HTMLOptGroupElement; -use crate::dom::htmloptionelement::HTMLOptionElement; -use crate::dom::htmloutputelement::HTMLOutputElement; -use crate::dom::htmlparagraphelement::HTMLParagraphElement; -use crate::dom::htmlparamelement::HTMLParamElement; -use crate::dom::htmlpictureelement::HTMLPictureElement; -use crate::dom::htmlpreelement::HTMLPreElement; -use crate::dom::htmlprogresselement::HTMLProgressElement; -use crate::dom::htmlquoteelement::HTMLQuoteElement; -use crate::dom::htmlscriptelement::HTMLScriptElement; -use crate::dom::htmlselectelement::HTMLSelectElement; -use crate::dom::htmlsourceelement::HTMLSourceElement; -use crate::dom::htmlspanelement::HTMLSpanElement; -use crate::dom::htmlstyleelement::HTMLStyleElement; -use crate::dom::htmltablecaptionelement::HTMLTableCaptionElement; -use crate::dom::htmltablecellelement::HTMLTableCellElement; -use crate::dom::htmltablecolelement::HTMLTableColElement; -use crate::dom::htmltableelement::HTMLTableElement; -use crate::dom::htmltablerowelement::HTMLTableRowElement; -use crate::dom::htmltablesectionelement::HTMLTableSectionElement; -use crate::dom::htmltemplateelement::HTMLTemplateElement; -use crate::dom::htmltextareaelement::HTMLTextAreaElement; -use crate::dom::htmltimeelement::HTMLTimeElement; -use crate::dom::htmltitleelement::HTMLTitleElement; -use crate::dom::htmltrackelement::HTMLTrackElement; -use crate::dom::htmlulistelement::HTMLUListElement; -use crate::dom::htmlunknownelement::HTMLUnknownElement; -use crate::dom::htmlvideoelement::HTMLVideoElement; -use crate::dom::svgsvgelement::SVGSVGElement; -use crate::script_thread::ScriptThread; +use dom::bindings::error::{report_pending_exception, throw_dom_exception}; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::DomRoot; +use dom::customelementregistry::{is_valid_custom_element_name, upgrade_element}; +use dom::document::Document; +use dom::element::{CustomElementCreationMode, CustomElementState, Element, ElementCreator}; +use dom::globalscope::GlobalScope; +use dom::htmlanchorelement::HTMLAnchorElement; +use dom::htmlareaelement::HTMLAreaElement; +use dom::htmlaudioelement::HTMLAudioElement; +use dom::htmlbaseelement::HTMLBaseElement; +use dom::htmlbodyelement::HTMLBodyElement; +use dom::htmlbrelement::HTMLBRElement; +use dom::htmlbuttonelement::HTMLButtonElement; +use dom::htmlcanvaselement::HTMLCanvasElement; +use dom::htmldataelement::HTMLDataElement; +use dom::htmldatalistelement::HTMLDataListElement; +use dom::htmldetailselement::HTMLDetailsElement; +use dom::htmldialogelement::HTMLDialogElement; +use dom::htmldirectoryelement::HTMLDirectoryElement; +use dom::htmldivelement::HTMLDivElement; +use dom::htmldlistelement::HTMLDListElement; +use dom::htmlelement::HTMLElement; +use dom::htmlembedelement::HTMLEmbedElement; +use dom::htmlfieldsetelement::HTMLFieldSetElement; +use dom::htmlfontelement::HTMLFontElement; +use dom::htmlformelement::HTMLFormElement; +use dom::htmlframeelement::HTMLFrameElement; +use dom::htmlframesetelement::HTMLFrameSetElement; +use dom::htmlheadelement::HTMLHeadElement; +use dom::htmlheadingelement::HTMLHeadingElement; +use dom::htmlheadingelement::HeadingLevel; +use dom::htmlhrelement::HTMLHRElement; +use dom::htmlhtmlelement::HTMLHtmlElement; +use dom::htmliframeelement::HTMLIFrameElement; +use dom::htmlimageelement::HTMLImageElement; +use dom::htmlinputelement::HTMLInputElement; +use dom::htmllabelelement::HTMLLabelElement; +use dom::htmllegendelement::HTMLLegendElement; +use dom::htmllielement::HTMLLIElement; +use dom::htmllinkelement::HTMLLinkElement; +use dom::htmlmapelement::HTMLMapElement; +use dom::htmlmetaelement::HTMLMetaElement; +use dom::htmlmeterelement::HTMLMeterElement; +use dom::htmlmodelement::HTMLModElement; +use dom::htmlobjectelement::HTMLObjectElement; +use dom::htmlolistelement::HTMLOListElement; +use dom::htmloptgroupelement::HTMLOptGroupElement; +use dom::htmloptionelement::HTMLOptionElement; +use dom::htmloutputelement::HTMLOutputElement; +use dom::htmlparagraphelement::HTMLParagraphElement; +use dom::htmlparamelement::HTMLParamElement; +use dom::htmlpictureelement::HTMLPictureElement; +use dom::htmlpreelement::HTMLPreElement; +use dom::htmlprogresselement::HTMLProgressElement; +use dom::htmlquoteelement::HTMLQuoteElement; +use dom::htmlscriptelement::HTMLScriptElement; +use dom::htmlselectelement::HTMLSelectElement; +use dom::htmlsourceelement::HTMLSourceElement; +use dom::htmlspanelement::HTMLSpanElement; +use dom::htmlstyleelement::HTMLStyleElement; +use dom::htmltablecaptionelement::HTMLTableCaptionElement; +use dom::htmltablecolelement::HTMLTableColElement; +use dom::htmltabledatacellelement::HTMLTableDataCellElement; +use dom::htmltableelement::HTMLTableElement; +use dom::htmltableheadercellelement::HTMLTableHeaderCellElement; +use dom::htmltablerowelement::HTMLTableRowElement; +use dom::htmltablesectionelement::HTMLTableSectionElement; +use dom::htmltemplateelement::HTMLTemplateElement; +use dom::htmltextareaelement::HTMLTextAreaElement; +use dom::htmltimeelement::HTMLTimeElement; +use dom::htmltitleelement::HTMLTitleElement; +use dom::htmltrackelement::HTMLTrackElement; +use dom::htmlulistelement::HTMLUListElement; +use dom::htmlunknownelement::HTMLUnknownElement; +use dom::htmlvideoelement::HTMLVideoElement; +use dom::svgsvgelement::SVGSVGElement; use html5ever::{LocalName, Prefix, QualName}; use js::jsapi::JSAutoCompartment; +use script_thread::ScriptThread; use servo_config::prefs::PREFS; fn create_svg_element( @@ -345,12 +346,12 @@ pub fn create_native_html_element( local_name!("sup") => make!(HTMLElement), local_name!("table") => make!(HTMLTableElement), local_name!("tbody") => make!(HTMLTableSectionElement), - local_name!("td") => make!(HTMLTableCellElement), + local_name!("td") => make!(HTMLTableDataCellElement), local_name!("template") => make!(HTMLTemplateElement), local_name!("textarea") => make!(HTMLTextAreaElement), // https://html.spec.whatwg.org/multipage/#the-tfoot-element:concept-element-dom local_name!("tfoot") => make!(HTMLTableSectionElement), - local_name!("th") => make!(HTMLTableCellElement), + local_name!("th") => make!(HTMLTableHeaderCellElement), // https://html.spec.whatwg.org/multipage/#the-thead-element:concept-element-dom local_name!("thead") => make!(HTMLTableSectionElement), local_name!("time") => make!(HTMLTimeElement), diff --git a/components/script/dom/crypto.rs b/components/script/dom/crypto.rs index a1c3f590e3c3..cc17c8a00f36 100644 --- a/components/script/dom/crypto.rs +++ b/components/script/dom/crypto.rs @@ -2,19 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CryptoBinding; -use crate::dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CryptoBinding; +use dom::bindings::codegen::Bindings::CryptoBinding::CryptoMethods; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use js::jsapi::Type; use js::jsapi::{JSContext, JSObject}; +use js::jsapi::Type; use js::rust::CustomAutoRooterGuard; use js::typedarray::ArrayBufferView; -use servo_rand::{Rng, ServoRng}; +use servo_rand::{ServoRng, Rng}; use std::ptr::NonNull; unsafe_no_jsmanaged_fields!(ServoRng); diff --git a/components/script/dom/css.rs b/components/script/dom/css.rs index 10f0bf9ae6dd..7a42d6b6e686 100644 --- a/components/script/dom/css.rs +++ b/components/script/dom/css.rs @@ -2,19 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::Reflector; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::window::Window; -use crate::dom::worklet::Worklet; -use cssparser::{serialize_identifier, Parser, ParserInput}; +use cssparser::{Parser, ParserInput, serialize_identifier}; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::Reflector; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::window::Window; +use dom::worklet::Worklet; use dom_struct::dom_struct; use style::context::QuirksMode; use style::parser::ParserContext; -use style::stylesheets::supports_rule::{parse_condition_or_declaration, Declaration}; use style::stylesheets::CssRuleType; +use style::stylesheets::supports_rule::{Declaration, parse_condition_or_declaration}; use style_traits::ParsingMode; #[dom_struct] @@ -53,21 +53,21 @@ impl CSS { pub fn Supports_(win: &Window, condition: DOMString) -> bool { let mut input = ParserInput::new(&condition); let mut input = Parser::new(&mut input); - let cond = match parse_condition_or_declaration(&mut input) { - Ok(c) => c, - Err(..) => return false, - }; - - let url = win.Document().url(); - let context = ParserContext::new_for_cssom( - &url, - Some(CssRuleType::Style), - ParsingMode::DEFAULT, - QuirksMode::NoQuirks, - None, - None, - ); - cond.eval(&context, &Default::default()) + let cond = parse_condition_or_declaration(&mut input); + if let Ok(cond) = cond { + let url = win.Document().url(); + let context = ParserContext::new_for_cssom( + &url, + Some(CssRuleType::Style), + ParsingMode::DEFAULT, + QuirksMode::NoQuirks, + None, + None, + ); + cond.eval(&context) + } else { + false + } } /// diff --git a/components/script/dom/cssconditionrule.rs b/components/script/dom/cssconditionrule.rs index 812a23cf2fcf..beef32f8a42f 100644 --- a/components/script/dom/cssconditionrule.rs +++ b/components/script/dom/cssconditionrule.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSConditionRuleBinding::CSSConditionRuleMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssgroupingrule::CSSGroupingRule; -use crate::dom::cssmediarule::CSSMediaRule; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::csssupportsrule::CSSSupportsRule; +use dom::bindings::codegen::Bindings::CSSConditionRuleBinding::CSSConditionRuleMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::str::DOMString; +use dom::cssgroupingrule::CSSGroupingRule; +use dom::cssmediarule::CSSMediaRule; +use dom::cssstylesheet::CSSStyleSheet; +use dom::csssupportsrule::CSSSupportsRule; use dom_struct::dom_struct; use servo_arc::Arc; -use style::shared_lock::{Locked, SharedRwLock}; +use style::shared_lock::{SharedRwLock, Locked}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] diff --git a/components/script/dom/cssfontfacerule.rs b/components/script/dom/cssfontfacerule.rs index 82fe5159ac67..5865ec760086 100644 --- a/components/script/dom/cssfontfacerule.rs +++ b/components/script/dom/cssfontfacerule.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSFontFaceRuleBinding; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSFontFaceRuleBinding; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; @@ -51,7 +51,7 @@ impl CSSFontFaceRule { impl SpecificCSSRule for CSSFontFaceRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::FONT_FACE_RULE } diff --git a/components/script/dom/cssgroupingrule.rs b/components/script/dom/cssgroupingrule.rs index f0010aa0e64a..9324035b0b07 100644 --- a/components/script/dom/cssgroupingrule.rs +++ b/components/script/dom/cssgroupingrule.rs @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods; -use crate::dom::bindings::error::{ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::CSSRule; -use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; -use crate::dom::cssstylesheet::CSSStyleSheet; +use dom::bindings::codegen::Bindings::CSSGroupingRuleBinding::CSSGroupingRuleMethods; +use dom::bindings::error::{ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::cssrule::CSSRule; +use dom::cssrulelist::{CSSRuleList, RulesSource}; +use dom::cssstylesheet::CSSStyleSheet; use dom_struct::dom_struct; use servo_arc::Arc; -use style::shared_lock::{Locked, SharedRwLock}; +use style::shared_lock::{SharedRwLock, Locked}; use style::stylesheets::CssRules as StyleCssRules; #[dom_struct] diff --git a/components/script/dom/cssimportrule.rs b/components/script/dom/cssimportrule.rs index 7ab8a4d5ac39..c8675c0457b0 100644 --- a/components/script/dom/cssimportrule.rs +++ b/components/script/dom/cssimportrule.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSImportRuleBinding; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSImportRuleBinding; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; @@ -48,7 +48,7 @@ impl CSSImportRule { impl SpecificCSSRule for CSSImportRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::IMPORT_RULE } diff --git a/components/script/dom/csskeyframerule.rs b/components/script/dom/csskeyframerule.rs index 4f253ea25721..7d5794474915 100644 --- a/components/script/dom/csskeyframerule.rs +++ b/components/script/dom/csskeyframerule.rs @@ -2,17 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{ - self, CSSKeyframeRuleMethods, -}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSKeyframeRuleBinding::{self, CSSKeyframeRuleMethods}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; @@ -75,7 +73,7 @@ impl CSSKeyframeRuleMethods for CSSKeyframeRule { impl SpecificCSSRule for CSSKeyframeRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::KEYFRAME_RULE } diff --git a/components/script/dom/csskeyframesrule.rs b/components/script/dom/csskeyframesrule.rs index 54b1780e0695..4c8902c6edd2 100644 --- a/components/script/dom/csskeyframesrule.rs +++ b/components/script/dom/csskeyframesrule.rs @@ -2,23 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding; -use crate::dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding::CSSKeyframesRuleMethods; -use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::csskeyframerule::CSSKeyframeRule; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; use cssparser::{Parser, ParserInput}; +use dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding; +use dom::bindings::codegen::Bindings::CSSKeyframesRuleBinding::CSSKeyframesRuleMethods; +use dom::bindings::error::ErrorResult; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::csskeyframerule::CSSKeyframeRule; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssrulelist::{CSSRuleList, RulesSource}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::keyframes_rule::{Keyframe, KeyframeSelector, KeyframesRule}; +use style::stylesheets::keyframes_rule::{KeyframesRule, Keyframe, KeyframeSelector}; use style::values::KeyframesName; #[dom_struct] @@ -146,7 +146,7 @@ impl CSSKeyframesRuleMethods for CSSKeyframesRule { impl SpecificCSSRule for CSSKeyframesRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::KEYFRAMES_RULE } diff --git a/components/script/dom/cssmediarule.rs b/components/script/dom/cssmediarule.rs index 3704168dd7b1..9c8bc87d89b1 100644 --- a/components/script/dom/cssmediarule.rs +++ b/components/script/dom/cssmediarule.rs @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSMediaRuleBinding; -use crate::dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssconditionrule::CSSConditionRule; -use crate::dom::cssrule::SpecificCSSRule; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::medialist::MediaList; -use crate::dom::window::Window; use cssparser::{Parser, ParserInput}; +use dom::bindings::codegen::Bindings::CSSMediaRuleBinding; +use dom::bindings::codegen::Bindings::CSSMediaRuleBinding::CSSMediaRuleMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::cssconditionrule::CSSConditionRule; +use dom::cssrule::SpecificCSSRule; +use dom::cssstylesheet::CSSStyleSheet; +use dom::medialist::MediaList; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::media_queries::MediaList as StyleMediaList; @@ -109,7 +109,7 @@ impl CSSMediaRule { impl SpecificCSSRule for CSSMediaRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::MEDIA_RULE } diff --git a/components/script/dom/cssnamespacerule.rs b/components/script/dom/cssnamespacerule.rs index c70939eeb368..b0340fecfebc 100644 --- a/components/script/dom/cssnamespacerule.rs +++ b/components/script/dom/cssnamespacerule.rs @@ -2,14 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; -use crate::dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding; +use dom::bindings::codegen::Bindings::CSSNamespaceRuleBinding::CSSNamespaceRuleMethods; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; @@ -71,7 +71,7 @@ impl CSSNamespaceRuleMethods for CSSNamespaceRule { impl SpecificCSSRule for CSSNamespaceRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::NAMESPACE_RULE } diff --git a/components/script/dom/cssrule.rs b/components/script/dom/cssrule.rs index 65ff5393a89e..71f8ab5844c6 100644 --- a/components/script/dom/cssrule.rs +++ b/components/script/dom/cssrule.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::Reflector; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssfontfacerule::CSSFontFaceRule; -use crate::dom::cssimportrule::CSSImportRule; -use crate::dom::csskeyframerule::CSSKeyframeRule; -use crate::dom::csskeyframesrule::CSSKeyframesRule; -use crate::dom::cssmediarule::CSSMediaRule; -use crate::dom::cssnamespacerule::CSSNamespaceRule; -use crate::dom::cssstylerule::CSSStyleRule; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::csssupportsrule::CSSSupportsRule; -use crate::dom::cssviewportrule::CSSViewportRule; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::Reflector; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::cssfontfacerule::CSSFontFaceRule; +use dom::cssimportrule::CSSImportRule; +use dom::csskeyframerule::CSSKeyframeRule; +use dom::csskeyframesrule::CSSKeyframesRule; +use dom::cssmediarule::CSSMediaRule; +use dom::cssnamespacerule::CSSNamespaceRule; +use dom::cssstylerule::CSSStyleRule; +use dom::cssstylesheet::CSSStyleSheet; +use dom::csssupportsrule::CSSSupportsRule; +use dom::cssviewportrule::CSSViewportRule; +use dom::window::Window; use dom_struct::dom_struct; use std::cell::Cell; use style::shared_lock::SharedRwLock; @@ -44,25 +44,25 @@ impl CSSRule { } } - pub fn as_specific(&self) -> &dyn SpecificCSSRule { + pub fn as_specific(&self) -> &SpecificCSSRule { if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else if let Some(rule) = self.downcast::() { - rule as &dyn SpecificCSSRule + rule as &SpecificCSSRule } else { unreachable!() } diff --git a/components/script/dom/cssrulelist.rs b/components/script/dom/cssrulelist.rs index 870a85866e88..f6668763e591 100644 --- a/components/script/dom/cssrulelist.rs +++ b/components/script/dom/cssrulelist.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding; -use crate::dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::csskeyframerule::CSSKeyframeRule; -use crate::dom::cssrule::CSSRule; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CSSRuleListBinding; +use dom::bindings::codegen::Bindings::CSSRuleListBinding::CSSRuleListMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::csskeyframerule::CSSKeyframeRule; +use dom::cssrule::CSSRule; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::Locked; diff --git a/components/script/dom/cssstyledeclaration.rs b/components/script/dom/cssstyledeclaration.rs index bc3fbe0f6554..795e401a5d3a 100644 --- a/components/script/dom/cssstyledeclaration.rs +++ b/components/script/dom/cssstyledeclaration.rs @@ -2,29 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{ - self, CSSStyleDeclarationMethods, -}; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::CSSRule; -use crate::dom::element::Element; -use crate::dom::node::{document_from_node, window_from_node, Node}; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSStyleDeclarationBinding::{self, CSSStyleDeclarationMethods}; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::cssrule::CSSRule; +use dom::element::Element; +use dom::node::{Node, window_from_node, document_from_node}; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use servo_url::ServoUrl; use style::attr::AttrValue; -use style::properties::{ - parse_one_declaration_into, parse_style_attribute, SourcePropertyDeclaration, -}; -use style::properties::{ - Importance, LonghandId, PropertyDeclarationBlock, PropertyId, ShorthandId, -}; +use style::properties::{Importance, PropertyDeclarationBlock, PropertyId, LonghandId, ShorthandId}; +use style::properties::{parse_one_declaration_into, parse_style_attribute, SourcePropertyDeclaration}; use style::selector_parser::PseudoElement; use style::shared_lock::Locked; use style_traits::ParsingMode; @@ -163,8 +157,7 @@ impl CSSStyleOwner { .style_stylesheet() .contents .url_data - .read()) - .clone(), + .read()).clone(), } } } diff --git a/components/script/dom/cssstylerule.rs b/components/script/dom/cssstylerule.rs index 0e9758f25fb8..788b72927b57 100644 --- a/components/script/dom/cssstylerule.rs +++ b/components/script/dom/cssstylerule.rs @@ -2,25 +2,25 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; -use cssparser::ToCss; use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; +use cssparser::ToCss; +use dom::bindings::codegen::Bindings::CSSStyleRuleBinding::{self, CSSStyleRuleMethods}; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use selectors::parser::SelectorList; use servo_arc::Arc; use std::mem; use style::selector_parser::SelectorParser; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::{Origin, StyleRule}; +use style::stylesheets::{StyleRule, Origin}; #[dom_struct] pub struct CSSStyleRule { @@ -58,7 +58,7 @@ impl CSSStyleRule { impl SpecificCSSRule for CSSStyleRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::STYLE_RULE } diff --git a/components/script/dom/cssstylesheet.rs b/components/script/dom/cssstylesheet.rs index 74b04a24dac4..def0f26bc776 100644 --- a/components/script/dom/cssstylesheet.rs +++ b/components/script/dom/cssstylesheet.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding; -use crate::dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrulelist::{CSSRuleList, RulesSource}; -use crate::dom::element::Element; -use crate::dom::stylesheet::StyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSStyleSheetBinding; +use dom::bindings::codegen::Bindings::CSSStyleSheetBinding::CSSStyleSheetMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::reflector::{reflect_dom_object, DomObject}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::cssrulelist::{CSSRuleList, RulesSource}; +use dom::element::Element; +use dom::stylesheet::StyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use std::cell::Cell; diff --git a/components/script/dom/cssstylevalue.rs b/components/script/dom/cssstylevalue.rs index bb19d351543e..2ecdbbe357f5 100644 --- a/components/script/dom/cssstylevalue.rs +++ b/components/script/dom/cssstylevalue.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; -use crate::dom::bindings::codegen::Bindings::CSSStyleValueBinding::Wrap; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::reflector::Reflector; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::globalscope::GlobalScope; use cssparser::Parser; use cssparser::ParserInput; +use dom::bindings::codegen::Bindings::CSSStyleValueBinding::CSSStyleValueMethods; +use dom::bindings::codegen::Bindings::CSSStyleValueBinding::Wrap; +use dom::bindings::reflector::Reflector; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use servo_url::ServoUrl; diff --git a/components/script/dom/csssupportsrule.rs b/components/script/dom/csssupportsrule.rs index b1a1e6b5be42..136a742e0e74 100644 --- a/components/script/dom/csssupportsrule.rs +++ b/components/script/dom/csssupportsrule.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssconditionrule::CSSConditionRule; -use crate::dom::cssrule::SpecificCSSRule; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; use cssparser::{Parser, ParserInput}; +use dom::bindings::codegen::Bindings::CSSSupportsRuleBinding; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::cssconditionrule::CSSConditionRule; +use dom::cssrule::SpecificCSSRule; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::parser::ParserContext; use style::shared_lock::{Locked, ToCssWithGuard}; -use style::stylesheets::supports_rule::SupportsCondition; use style::stylesheets::{CssRuleType, SupportsRule}; +use style::stylesheets::supports_rule::SupportsCondition; use style_traits::{ParsingMode, ToCss}; #[dom_struct] @@ -81,16 +81,7 @@ impl CSSSupportsRule { None, None, ); - let enabled = { - let namespaces = self - .cssconditionrule - .parent_stylesheet() - .style_stylesheet() - .contents - .namespaces - .read(); - cond.eval(&context, &namespaces) - }; + let enabled = cond.eval(&context); let mut guard = self.cssconditionrule.shared_lock().write(); let rule = self.supportsrule.write_with(&mut guard); rule.condition = cond; @@ -101,7 +92,7 @@ impl CSSSupportsRule { impl SpecificCSSRule for CSSSupportsRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::SUPPORTS_RULE } diff --git a/components/script/dom/cssviewportrule.rs b/components/script/dom/cssviewportrule.rs index 9c19033601d8..8f0dbaa8c152 100644 --- a/components/script/dom/cssviewportrule.rs +++ b/components/script/dom/cssviewportrule.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CSSViewportRuleBinding; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssrule::{CSSRule, SpecificCSSRule}; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::CSSViewportRuleBinding; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::cssrule::{CSSRule, SpecificCSSRule}; +use dom::cssstylesheet::CSSStyleSheet; +use dom::window::Window; use dom_struct::dom_struct; use servo_arc::Arc; use style::shared_lock::{Locked, ToCssWithGuard}; @@ -51,7 +51,7 @@ impl CSSViewportRule { impl SpecificCSSRule for CSSViewportRule { fn ty(&self) -> u16 { - use crate::dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; + use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::VIEWPORT_RULE } diff --git a/components/script/dom/customelementregistry.rs b/components/script/dom/customelementregistry.rs index 8de16faf1d69..7239a99b0c08 100644 --- a/components/script/dom/customelementregistry.rs +++ b/components/script/dom/customelementregistry.rs @@ -2,44 +2,40 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::callback::{CallbackContainer, ExceptionHandling}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding; -use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementConstructor; -use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementRegistryMethods; -use crate::dom::bindings::codegen::Bindings::CustomElementRegistryBinding::ElementDefinitionOptions; -use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; -use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; -use crate::dom::bindings::conversions::{ - ConversionResult, FromJSValConvertible, StringificationBehavior, -}; -use crate::dom::bindings::error::{ - report_pending_exception, throw_dom_exception, Error, ErrorResult, Fallible, -}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::domexception::{DOMErrorName, DOMException}; -use crate::dom::element::{CustomElementState, Element}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, window_from_node, Node}; -use crate::dom::promise::Promise; -use crate::dom::window::Window; -use crate::microtask::Microtask; -use crate::script_thread::ScriptThread; +use dom::bindings::callback::{CallbackContainer, ExceptionHandling}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CustomElementRegistryBinding; +use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementConstructor; +use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::CustomElementRegistryMethods; +use dom::bindings::codegen::Bindings::CustomElementRegistryBinding::ElementDefinitionOptions; +use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; +use dom::bindings::codegen::Bindings::FunctionBinding::Function; +use dom::bindings::codegen::Bindings::WindowBinding::WindowBinding::WindowMethods; +use dom::bindings::conversions::{ConversionResult, FromJSValConvertible, StringificationBehavior}; +use dom::bindings::error::{Error, ErrorResult, Fallible, report_pending_exception, throw_dom_exception}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::domexception::{DOMErrorName, DOMException}; +use dom::element::{CustomElementState, Element}; +use dom::globalscope::GlobalScope; +use dom::htmlelement::HTMLElement; +use dom::node::{document_from_node, Node, window_from_node}; +use dom::promise::Promise; +use dom::window::Window; use dom_struct::dom_struct; use html5ever::{LocalName, Namespace, Prefix}; use js::conversions::ToJSValConvertible; use js::glue::UnwrapObject; -use js::jsapi::{HandleValueArray, Heap, IsCallable, IsConstructor}; +use js::jsapi::{Heap, IsCallable, IsConstructor, HandleValueArray}; use js::jsapi::{JSAutoCompartment, JSContext, JSObject}; use js::jsval::{JSVal, NullValue, ObjectValue, UndefinedValue}; -use js::rust::wrappers::{Construct1, JS_GetProperty, JS_SameValue}; use js::rust::{HandleObject, HandleValue, MutableHandleValue}; +use js::rust::wrappers::{JS_GetProperty, Construct1, JS_SameValue}; +use microtask::Microtask; +use script_thread::ScriptThread; use std::cell::Cell; use std::collections::{HashMap, VecDeque}; use std::mem; @@ -101,8 +97,7 @@ impl CustomElementRegistry { // Step 4-5 definition.local_name == *local_name && (definition.name == *local_name || Some(&definition.name) == is) - }) - .cloned() + }).cloned() } pub fn lookup_definition_by_constructor( diff --git a/components/script/dom/customevent.rs b/components/script/dom/customevent.rs index 3a4a4e78a3ad..b054d1a0dcb0 100644 --- a/components/script/dom/customevent.rs +++ b/components/script/dom/customevent.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::CustomEventBinding; -use crate::dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::RootedTraceableBox; -use crate::dom::event::Event; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::CustomEventBinding; +use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::bindings::trace::RootedTraceableBox; +use dom::event::Event; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext}; use js::jsval::JSVal; diff --git a/components/script/dom/dedicatedworkerglobalscope.rs b/components/script/dom/dedicatedworkerglobalscope.rs index f9a3debe9b4a..dac95aeb4c54 100644 --- a/components/script/dom/dedicatedworkerglobalscope.rs +++ b/components/script/dom/dedicatedworkerglobalscope.rs @@ -2,50 +2,50 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::devtools; -use crate::dom::abstractworker::{SimpleWorkerErrorHandler, WorkerScriptMsg}; -use crate::dom::abstractworkerglobalscope::{run_worker_event_loop, WorkerEventLoopMethods}; -use crate::dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; -use crate::dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; -use crate::dom::bindings::error::{ErrorInfo, ErrorResult}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{DomRoot, RootCollection, ThreadLocalStackRoots}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::structuredclone::StructuredCloneData; -use crate::dom::errorevent::ErrorEvent; -use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::messageevent::MessageEvent; -use crate::dom::worker::{TrustedWorkerAddress, Worker}; -use crate::dom::workerglobalscope::WorkerGlobalScope; -use crate::script_runtime::ScriptThreadEventCategory::WorkerEvent; -use crate::script_runtime::{new_rt_and_cx, CommonScriptMsg, Runtime, ScriptChan, ScriptPort}; -use crate::task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; -use crate::task_source::TaskSourceName; +use devtools; use devtools_traits::DevtoolScriptControlMsg; +use dom::abstractworker::{SimpleWorkerErrorHandler, WorkerScriptMsg}; +use dom::abstractworkerglobalscope::{SendableWorkerScriptChan, WorkerThreadWorkerChan}; +use dom::abstractworkerglobalscope::{WorkerEventLoopMethods, run_worker_event_loop}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding; +use dom::bindings::codegen::Bindings::DedicatedWorkerGlobalScopeBinding::DedicatedWorkerGlobalScopeMethods; +use dom::bindings::error::{ErrorInfo, ErrorResult}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{DomRoot, RootCollection, ThreadLocalStackRoots}; +use dom::bindings::str::DOMString; +use dom::bindings::structuredclone::StructuredCloneData; +use dom::errorevent::ErrorEvent; +use dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::messageevent::MessageEvent; +use dom::worker::{TrustedWorkerAddress, Worker}; +use dom::workerglobalscope::WorkerGlobalScope; use dom_struct::dom_struct; use ipc_channel::ipc::{self, IpcReceiver, IpcSender}; use ipc_channel::router::ROUTER; -use js::jsapi::JS_AddInterruptCallback; use js::jsapi::{JSAutoCompartment, JSContext}; +use js::jsapi::JS_AddInterruptCallback; use js::jsval::UndefinedValue; use js::rust::HandleValue; use msg::constellation_msg::TopLevelBrowsingContextId; +use net_traits::{IpcSend, load_whole_resource}; use net_traits::request::{CredentialsMode, Destination, RequestInit}; -use net_traits::{load_whole_resource, IpcSend}; +use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort, new_rt_and_cx, Runtime}; +use script_runtime::ScriptThreadEventCategory::WorkerEvent; use script_traits::{TimerEvent, TimerSource, WorkerGlobalScopeInit, WorkerScriptLoadOrigin}; -use servo_channel::{channel, route_ipc_receiver_to_new_servo_sender, Receiver, Sender}; +use servo_channel::{channel, route_ipc_receiver_to_new_servo_sender, Sender, Receiver}; use servo_rand::random; use servo_url::ServoUrl; use std::mem::replace; -use std::sync::atomic::AtomicBool; use std::sync::Arc; +use std::sync::atomic::AtomicBool; use std::thread; use style::thread_state::{self, ThreadState}; +use task_queue::{QueuedTask, QueuedTaskConversion, TaskQueue}; +use task_source::TaskSourceName; /// Set the `worker` field of a related DedicatedWorkerGlobalScope object to a particular /// value for the duration of this object's lifetime. This ensures that the related Worker @@ -203,7 +203,7 @@ impl DedicatedWorkerGlobalScope { worker_url: ServoUrl, from_devtools_receiver: Receiver, runtime: Runtime, - parent_sender: Box, + parent_sender: Box, own_sender: Sender, receiver: Receiver, timer_event_chan: IpcSender, @@ -233,7 +233,7 @@ impl DedicatedWorkerGlobalScope { worker_url: ServoUrl, from_devtools_receiver: Receiver, runtime: Runtime, - parent_sender: Box, + parent_sender: Box, own_sender: Sender, receiver: Receiver, timer_event_chan: IpcSender, @@ -263,7 +263,7 @@ impl DedicatedWorkerGlobalScope { worker_url: ServoUrl, from_devtools_receiver: IpcReceiver, worker: TrustedWorkerAddress, - parent_sender: Box, + parent_sender: Box, own_sender: Sender, receiver: Receiver, worker_load_origin: WorkerScriptLoadOrigin, @@ -318,8 +318,7 @@ impl DedicatedWorkerGlobalScope { Box::new(SimpleWorkerErrorHandler::new(worker)), pipeline_id, TaskSourceName::DOMManipulation, - )) - .unwrap(); + )).unwrap(); return; }, Ok((metadata, bytes)) => (metadata, bytes), @@ -392,18 +391,17 @@ impl DedicatedWorkerGlobalScope { parent_sender, CommonScriptMsg::CollectReports, ); - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); } - pub fn script_chan(&self) -> Box { + pub fn script_chan(&self) -> Box { Box::new(WorkerThreadWorkerChan { sender: self.own_sender.clone(), worker: self.worker.borrow().as_ref().unwrap().clone(), }) } - pub fn new_script_pair(&self) -> (Box, Box) { + pub fn new_script_pair(&self) -> (Box, Box) { let (tx, rx) = channel(); let chan = Box::new(SendableWorkerScriptChan { sender: tx, @@ -497,8 +495,7 @@ impl DedicatedWorkerGlobalScope { task, Some(pipeline_id), TaskSourceName::DOMManipulation, - )) - .unwrap(); + )).unwrap(); } } @@ -529,8 +526,7 @@ impl DedicatedWorkerGlobalScopeMethods for DedicatedWorkerGlobalScope { task, Some(pipeline_id), TaskSourceName::DOMManipulation, - )) - .unwrap(); + )).unwrap(); Ok(()) } diff --git a/components/script/dom/dissimilaroriginlocation.rs b/components/script/dom/dissimilaroriginlocation.rs index e2111008eb3e..0f8fe5bd3949 100644 --- a/components/script/dom/dissimilaroriginlocation.rs +++ b/components/script/dom/dissimilaroriginlocation.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding; -use crate::dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding::DissimilarOriginLocationMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::reflector::Reflector; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::str::USVString; -use crate::dom::dissimilaroriginwindow::DissimilarOriginWindow; +use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding; +use dom::bindings::codegen::Bindings::DissimilarOriginLocationBinding::DissimilarOriginLocationMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::reflector::Reflector; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::bindings::str::USVString; +use dom::dissimilaroriginwindow::DissimilarOriginWindow; use dom_struct::dom_struct; use servo_url::MutableOrigin; diff --git a/components/script/dom/dissimilaroriginwindow.rs b/components/script/dom/dissimilaroriginwindow.rs index 417c0d82f72a..40897b2bf522 100644 --- a/components/script/dom/dissimilaroriginwindow.rs +++ b/components/script/dom/dissimilaroriginwindow.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding; -use crate::dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods; -use crate::dom::bindings::error::{Error, ErrorResult}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::structuredclone::StructuredCloneData; -use crate::dom::dissimilaroriginlocation::DissimilarOriginLocation; -use crate::dom::globalscope::GlobalScope; -use crate::dom::windowproxy::WindowProxy; +use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding; +use dom::bindings::codegen::Bindings::DissimilarOriginWindowBinding::DissimilarOriginWindowMethods; +use dom::bindings::error::{Error, ErrorResult}; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::bindings::structuredclone::StructuredCloneData; +use dom::dissimilaroriginlocation::DissimilarOriginLocation; +use dom::globalscope::GlobalScope; +use dom::windowproxy::WindowProxy; use dom_struct::dom_struct; use ipc_channel::ipc; use js::jsapi::JSContext; diff --git a/components/script/dom/document.rs b/components/script/dom/document.rs index 36156a1d89f7..d68f085af831 100644 --- a/components/script/dom/document.rs +++ b/components/script/dom/document.rs @@ -2,134 +2,120 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use cookie::Cookie; -use crate::document_loader::{DocumentLoader, LoadType}; -use crate::dom::activation::{synthetic_click_activation, ActivationSource}; -use crate::dom::attr::Attr; -use crate::dom::beforeunloadevent::BeforeUnloadEvent; -use crate::dom::bindings::callback::ExceptionHandling; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventBinding::BeforeUnloadEventMethods; -use crate::dom::bindings::codegen::Bindings::DocumentBinding; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::ElementCreationOptions; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ - DocumentMethods, DocumentReadyState, -}; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; -use crate::dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementBinding::HTMLIFrameElementMethods; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use crate::dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter; -use crate::dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; -use crate::dom::bindings::codegen::Bindings::TouchBinding::TouchMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::{ - FrameRequestCallback, ScrollBehavior, WindowMethods, -}; -use crate::dom::bindings::codegen::UnionTypes::NodeOrString; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; -use crate::dom::bindings::xmlname::{ - namespace_from_domstring, validate_and_extract, xml_name_type, -}; -use crate::dom::closeevent::CloseEvent; -use crate::dom::comment::Comment; -use crate::dom::cssstylesheet::CSSStyleSheet; -use crate::dom::customelementregistry::CustomElementDefinition; -use crate::dom::customevent::CustomEvent; -use crate::dom::documentfragment::DocumentFragment; -use crate::dom::documenttype::DocumentType; -use crate::dom::domimplementation::DOMImplementation; -use crate::dom::element::CustomElementCreationMode; -use crate::dom::element::{ - Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit, -}; -use crate::dom::errorevent::ErrorEvent; -use crate::dom::event::{Event, EventBubbles, EventCancelable, EventDefault, EventStatus}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::focusevent::FocusEvent; -use crate::dom::globalscope::GlobalScope; -use crate::dom::hashchangeevent::HashChangeEvent; -use crate::dom::htmlanchorelement::HTMLAnchorElement; -use crate::dom::htmlareaelement::HTMLAreaElement; -use crate::dom::htmlbaseelement::HTMLBaseElement; -use crate::dom::htmlbodyelement::HTMLBodyElement; -use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmlembedelement::HTMLEmbedElement; -use crate::dom::htmlformelement::{FormControl, FormControlElementHelpers, HTMLFormElement}; -use crate::dom::htmlheadelement::HTMLHeadElement; -use crate::dom::htmlhtmlelement::HTMLHtmlElement; -use crate::dom::htmliframeelement::HTMLIFrameElement; -use crate::dom::htmlimageelement::HTMLImageElement; -use crate::dom::htmlmetaelement::HTMLMetaElement; -use crate::dom::htmlscriptelement::{HTMLScriptElement, ScriptResult}; -use crate::dom::htmltitleelement::HTMLTitleElement; -use crate::dom::keyboardevent::KeyboardEvent; -use crate::dom::location::Location; -use crate::dom::messageevent::MessageEvent; -use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::VecPreOrderInsertionHelper; -use crate::dom::node::{self, document_from_node, window_from_node, CloneChildrenFlag}; -use crate::dom::node::{LayoutNodeHelpers, Node, NodeDamage, NodeFlags}; -use crate::dom::nodeiterator::NodeIterator; -use crate::dom::nodelist::NodeList; -use crate::dom::pagetransitionevent::PageTransitionEvent; -use crate::dom::popstateevent::PopStateEvent; -use crate::dom::processinginstruction::ProcessingInstruction; -use crate::dom::progressevent::ProgressEvent; -use crate::dom::promise::Promise; -use crate::dom::range::Range; -use crate::dom::servoparser::ServoParser; -use crate::dom::storageevent::StorageEvent; -use crate::dom::stylesheetlist::StyleSheetList; -use crate::dom::text::Text; -use crate::dom::touch::Touch; -use crate::dom::touchevent::TouchEvent; -use crate::dom::touchlist::TouchList; -use crate::dom::treewalker::TreeWalker; -use crate::dom::uievent::UIEvent; -use crate::dom::virtualmethods::vtable_for; -use crate::dom::webglcontextevent::WebGLContextEvent; -use crate::dom::window::{ReflowReason, Window}; -use crate::dom::windowproxy::WindowProxy; -use crate::fetch::FetchCanceller; -use crate::script_runtime::{CommonScriptMsg, ScriptThreadEventCategory}; -use crate::script_thread::{MainThreadScriptMsg, ScriptThread}; -use crate::task_source::{TaskSource, TaskSourceName}; -use crate::timers::OneshotTimerCallback; +use cookie_rs; use devtools_traits::ScriptToDevtoolsControlMsg; +use document_loader::{DocumentLoader, LoadType}; +use dom::activation::{ActivationSource, synthetic_click_activation}; +use dom::attr::Attr; +use dom::beforeunloadevent::BeforeUnloadEvent; +use dom::bindings::callback::ExceptionHandling; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventBinding::BeforeUnloadEventMethods; +use dom::bindings::codegen::Bindings::DocumentBinding; +use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, DocumentReadyState, ElementCreationOptions}; +use dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::HTMLIFrameElementBinding::HTMLIFrameElementBinding::HTMLIFrameElementMethods; +use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; +use dom::bindings::codegen::Bindings::NodeFilterBinding::NodeFilter; +use dom::bindings::codegen::Bindings::PerformanceBinding::PerformanceMethods; +use dom::bindings::codegen::Bindings::TouchBinding::TouchMethods; +use dom::bindings::codegen::Bindings::WindowBinding::{FrameRequestCallback, ScrollBehavior, WindowMethods}; +use dom::bindings::codegen::UnionTypes::NodeOrString; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; +use dom::bindings::num::Finite; +use dom::bindings::refcounted::{Trusted, TrustedPromise}; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; +use dom::bindings::str::{DOMString, USVString}; +use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; +use dom::bindings::xmlname::XMLName::InvalidXMLName; +use dom::closeevent::CloseEvent; +use dom::comment::Comment; +use dom::cssstylesheet::CSSStyleSheet; +use dom::customelementregistry::CustomElementDefinition; +use dom::customevent::CustomEvent; +use dom::documentfragment::DocumentFragment; +use dom::documenttype::DocumentType; +use dom::domimplementation::DOMImplementation; +use dom::element::{Element, ElementCreator, ElementPerformFullscreenEnter, ElementPerformFullscreenExit}; +use dom::element::CustomElementCreationMode; +use dom::errorevent::ErrorEvent; +use dom::event::{Event, EventBubbles, EventCancelable, EventDefault, EventStatus}; +use dom::eventtarget::EventTarget; +use dom::focusevent::FocusEvent; +use dom::globalscope::GlobalScope; +use dom::hashchangeevent::HashChangeEvent; +use dom::htmlanchorelement::HTMLAnchorElement; +use dom::htmlareaelement::HTMLAreaElement; +use dom::htmlbaseelement::HTMLBaseElement; +use dom::htmlbodyelement::HTMLBodyElement; +use dom::htmlcollection::{CollectionFilter, HTMLCollection}; +use dom::htmlelement::HTMLElement; +use dom::htmlembedelement::HTMLEmbedElement; +use dom::htmlformelement::{FormControl, FormControlElementHelpers, HTMLFormElement}; +use dom::htmlheadelement::HTMLHeadElement; +use dom::htmlhtmlelement::HTMLHtmlElement; +use dom::htmliframeelement::HTMLIFrameElement; +use dom::htmlimageelement::HTMLImageElement; +use dom::htmlmetaelement::HTMLMetaElement; +use dom::htmlscriptelement::{HTMLScriptElement, ScriptResult}; +use dom::htmltitleelement::HTMLTitleElement; +use dom::keyboardevent::KeyboardEvent; +use dom::location::Location; +use dom::messageevent::MessageEvent; +use dom::mouseevent::MouseEvent; +use dom::node::{self, CloneChildrenFlag, document_from_node, window_from_node}; +use dom::node::{Node, NodeDamage, NodeFlags, LayoutNodeHelpers}; +use dom::node::VecPreOrderInsertionHelper; +use dom::nodeiterator::NodeIterator; +use dom::nodelist::NodeList; +use dom::pagetransitionevent::PageTransitionEvent; +use dom::popstateevent::PopStateEvent; +use dom::processinginstruction::ProcessingInstruction; +use dom::progressevent::ProgressEvent; +use dom::promise::Promise; +use dom::range::Range; +use dom::servoparser::ServoParser; +use dom::storageevent::StorageEvent; +use dom::stylesheetlist::StyleSheetList; +use dom::text::Text; +use dom::touch::Touch; +use dom::touchevent::TouchEvent; +use dom::touchlist::TouchList; +use dom::treewalker::TreeWalker; +use dom::uievent::UIEvent; +use dom::virtualmethods::vtable_for; +use dom::webglcontextevent::WebGLContextEvent; +use dom::window::{ReflowReason, Window}; +use dom::windowproxy::WindowProxy; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use encoding_rs::{Encoding, UTF_8}; use euclid::Point2D; +use fetch::FetchCanceller; use html5ever::{LocalName, Namespace, QualName}; +use hyper::header::{Header, SetCookie}; use hyper_serde::Serde; use ipc_channel::ipc::{self, IpcSender}; -use js::jsapi::JS_GetRuntime; use js::jsapi::{JSContext, JSObject, JSRuntime}; -use keyboard_types::{Key, KeyState, Modifiers}; -use metrics::{ - InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, - ProgressiveWebMetric, -}; -use mime::{self, Mime}; -use msg::constellation_msg::BrowsingContextId; +use js::jsapi::JS_GetRuntime; +use metrics::{InteractiveFlag, InteractiveMetrics, InteractiveWindow, ProfilerMetadataFactory, ProgressiveWebMetric}; +use mime::{Mime, TopLevel, SubLevel}; +use msg::constellation_msg::{BrowsingContextId, Key, KeyModifiers, KeyState}; +use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy}; +use net_traits::CookieSource::NonHTTP; +use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl}; use net_traits::pub_domains::is_pub_domain; use net_traits::request::RequestInit; use net_traits::response::HttpsState; -use net_traits::CookieSource::NonHTTP; -use net_traits::CoreResourceMsg::{GetCookiesForUrl, SetCookiesForUrl}; -use net_traits::{FetchResponseMsg, IpcSend, ReferrerPolicy}; use num_traits::ToPrimitive; use profile_traits::ipc as profile_ipc; use profile_traits::time::{TimerMetadata, TimerMetadataFrameType, TimerMetadataReflowType}; use ref_slice::ref_slice; use script_layout_interface::message::{Msg, NodesFromPointQueryType, QueryMsg, ReflowGoal}; +use script_runtime::{CommonScriptMsg, ScriptThreadEventCategory}; +use script_thread::{MainThreadScriptMsg, ScriptThread}; use script_traits::{AnimationState, DocumentActivity, MouseButton, MouseEventType}; use script_traits::{MsDuration, ScriptMsg, TouchEventType, TouchId, UntrustedNodeAddress}; use servo_arc::Arc; @@ -138,8 +124,8 @@ use servo_config::prefs::PREFS; use servo_url::{ImmutableOrigin, MutableOrigin, ServoUrl}; use std::borrow::ToOwned; use std::cell::{Cell, Ref, RefMut}; -use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::{HashMap, HashSet, VecDeque}; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::default::Default; use std::fmt; use std::mem; @@ -154,9 +140,12 @@ use style::selector_parser::{RestyleDamage, Snapshot}; use style::shared_lock::{SharedRwLock as StyleSharedRwLock, SharedRwLockReadGuard}; use style::str::{split_html_space_chars, str_join}; use style::stylesheet_set::DocumentStylesheetSet; -use style::stylesheets::{CssRule, Origin, OriginSet, Stylesheet}; -use url::percent_encoding::percent_decode; +use style::stylesheets::{CssRule, Stylesheet, Origin, OriginSet}; +use task_source::{TaskSource, TaskSourceName}; +use time; +use timers::OneshotTimerCallback; use url::Host; +use url::percent_encoding::percent_decode; /// The number of times we are allowed to see spurious `requestAnimationFrame()` calls before /// falling back to fake ones. @@ -549,8 +538,7 @@ impl Document { ); }), self.window.upcast(), - ) - .unwrap(); + ).unwrap(); } } else { self.window().suspend(); @@ -781,12 +769,10 @@ impl Document { // Step 1 is not handled here; the fragid is already obtained by the calling function // Step 2: Simply use None to indicate the top of the document. // Step 3 & 4 - percent_decode(fragid.as_bytes()) - .decode_utf8() - .ok() - // Step 5 + percent_decode(fragid.as_bytes()).decode_utf8().ok() + // Step 5 .and_then(|decoded_fragid| self.get_element_by_id(&Atom::from(decoded_fragid))) - // Step 6 + // Step 6 .or_else(|| self.get_anchor_by_name(fragid)) // Step 7 & 8 } @@ -819,8 +805,7 @@ impl Document { rect.origin.x.to_nearest_px() as f32, rect.origin.y.to_nearest_px() as f32, ) - }) - .or_else(|| { + }).or_else(|| { if fragment.is_empty() || fragment.eq_ignore_ascii_case("top") { // FIXME(stshine): this should be the origin of the stacking context space, // which may differ under the influence of writing mode. @@ -1363,7 +1348,13 @@ impl Document { } /// The entry point for all key processing for web content - pub fn dispatch_key_event(&self, keyboard_event: ::keyboard_types::KeyboardEvent) { + pub fn dispatch_key_event( + &self, + ch: Option, + key: Key, + state: KeyState, + modifiers: KeyModifiers, + ) { let focused = self.get_focused_element(); let body = self.GetBody(); @@ -1373,29 +1364,50 @@ impl Document { (&None, &None) => self.window.upcast(), }; + let ctrl = modifiers.contains(KeyModifiers::CONTROL); + let alt = modifiers.contains(KeyModifiers::ALT); + let shift = modifiers.contains(KeyModifiers::SHIFT); + let meta = modifiers.contains(KeyModifiers::SUPER); + + let is_composing = false; + let is_repeating = state == KeyState::Repeated; + let ev_type = DOMString::from( + match state { + KeyState::Pressed | KeyState::Repeated => "keydown", + KeyState::Released => "keyup", + }.to_owned(), + ); + + let props = KeyboardEvent::key_properties(ch, key, modifiers); + let keyevent = KeyboardEvent::new( &self.window, - DOMString::from(keyboard_event.state.to_string()), + ev_type, true, true, Some(&self.window), 0, - keyboard_event.key.clone(), - DOMString::from(keyboard_event.code.to_string()), - keyboard_event.location as u32, - keyboard_event.repeat, - keyboard_event.is_composing, - keyboard_event.modifiers, - 0, - keyboard_event.key.legacy_keycode(), + ch, + Some(key), + DOMString::from(props.key_string.clone()), + DOMString::from(props.code), + props.location, + is_repeating, + is_composing, + ctrl, + alt, + shift, + meta, + None, + props.key_code, ); let event = keyevent.upcast::(); event.fire(target); let mut cancel_state = event.get_cancel_state(); // https://w3c.github.io/uievents/#keys-cancelable-keys - if keyboard_event.state == KeyState::Down && - keyboard_event.key.legacy_charcode() != 0 && + if state != KeyState::Released && + props.is_printable() && cancel_state != EventDefault::Prevented { // https://w3c.github.io/uievents/#keypress-event-order @@ -1406,13 +1418,18 @@ impl Document { true, Some(&self.window), 0, - keyboard_event.key.clone(), - DOMString::from(keyboard_event.code.to_string()), - keyboard_event.location as u32, - keyboard_event.repeat, - keyboard_event.is_composing, - keyboard_event.modifiers, - keyboard_event.key.legacy_charcode(), + ch, + Some(key), + DOMString::from(props.key_string), + DOMString::from(props.code), + props.location, + is_repeating, + is_composing, + ctrl, + alt, + shift, + meta, + props.char_code, 0, ); let ev = event.upcast::(); @@ -1421,7 +1438,7 @@ impl Document { } if cancel_state == EventDefault::Allowed { - let msg = EmbedderMsg::Keyboard(keyboard_event.clone()); + let msg = EmbedderMsg::KeyEvent(ch, key, state, modifiers); self.send_to_embedder(msg); // This behavior is unspecced @@ -1429,10 +1446,8 @@ impl Document { // however *when* we do it is up to us. // Here, we're dispatching it after the key event so the script has a chance to cancel it // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27337 - match keyboard_event.key { - Key::Character(ref letter) - if letter == " " && keyboard_event.state == KeyState::Up => - { + match key { + Key::Space if state == KeyState::Released => { let maybe_elem = target.downcast::(); if let Some(el) = maybe_elem { synthetic_click_activation( @@ -1444,15 +1459,11 @@ impl Document { ActivationSource::NotFromClick, ) } - } - Key::Enter if keyboard_event.state == KeyState::Up => { + }, + Key::Enter if state == KeyState::Released => { let maybe_elem = target.downcast::(); if let Some(el) = maybe_elem { if let Some(a) = el.as_maybe_activatable() { - let ctrl = keyboard_event.modifiers.contains(Modifiers::CONTROL); - let alt = keyboard_event.modifiers.contains(Modifiers::ALT); - let shift = keyboard_event.modifiers.contains(Modifiers::SHIFT); - let meta = keyboard_event.modifiers.contains(Modifiers::META); a.implicit_submission(ctrl, alt, shift, meta); } } @@ -1915,8 +1926,7 @@ impl Document { } }), self.window.upcast(), - ) - .unwrap(); + ).unwrap(); // Step 8. let document = Trusted::new(self); @@ -1950,8 +1960,7 @@ impl Document { ); }), self.window.upcast(), - ) - .unwrap(); + ).unwrap(); } // Step 9. @@ -2543,12 +2552,14 @@ impl Document { implementation: Default::default(), content_type: match content_type { Some(mime_data) => mime_data, - None => match is_html_document { + None => Mime::from(match is_html_document { // https://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument - IsHTMLDocument::HTMLDocument => mime::TEXT_HTML, + IsHTMLDocument::HTMLDocument => Mime(TopLevel::Text, SubLevel::Html, vec![]), // https://dom.spec.whatwg.org/#concept-document-content-type - IsHTMLDocument::NonHTMLDocument => "application/xml".parse().unwrap(), - }, + IsHTMLDocument::NonHTMLDocument => { + Mime(TopLevel::Application, SubLevel::Xml, vec![]) + }, + }), }, last_modified: last_modified, url: DomRefCell::new(url), @@ -2793,16 +2804,14 @@ impl Document { owner .upcast::() .is_before(sheet_in_doc.owner.upcast()) - }) - .cloned(); + }).cloned(); self.window() .layout_chan() .send(Msg::AddStylesheet( sheet.clone(), insertion_point.as_ref().map(|s| s.sheet.clone()), - )) - .unwrap(); + )).unwrap(); let sheet = StyleSheetInDocument { sheet, @@ -3358,10 +3367,8 @@ impl DocumentMethods for Document { local_name.make_ascii_lowercase(); } - let is_xhtml = self.content_type.type_() == mime::APPLICATION && - self.content_type.subtype().as_str() == "xhtml" && - self.content_type.suffix() == Some(mime::XML); - + let is_xhtml = self.content_type.0 == TopLevel::Application && + self.content_type.1.as_str() == "xhtml+xml"; let ns = if self.is_html_document || is_xhtml { ns!(html) } else { @@ -3636,8 +3643,7 @@ impl DocumentMethods for Document { .child_elements() .find(|node| { node.namespace() == &ns!(svg) && node.local_name() == &local_name!("title") - }) - .map(DomRoot::upcast::) + }).map(DomRoot::upcast::) } else { // Step 2. root.upcast::() @@ -3742,8 +3748,7 @@ impl DocumentMethods for Document { HTMLElementTypeId::HTMLFrameSetElement, )) => true, _ => false, - }) - .map(|node| DomRoot::downcast(node).unwrap()) + }).map(|node| DomRoot::downcast(node).unwrap()) }) } @@ -3964,17 +3969,18 @@ impl DocumentMethods for Document { return Err(Error::Security); } - let cookies = if let Some(cookie) = Cookie::parse(cookie.to_string()).ok().map(Serde) { - vec![cookie] - } else { - vec![] - }; - - let _ = self - .window - .upcast::() - .resource_threads() - .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); + if let Ok(cookie_header) = SetCookie::parse_header(&vec![cookie.to_string().into_bytes()]) { + let cookies = cookie_header + .0 + .into_iter() + .filter_map(|cookie| cookie_rs::Cookie::parse(cookie).ok().map(Serde)) + .collect(); + let _ = self + .window + .upcast::() + .resource_threads() + .send(SetCookiesForUrl(self.url(), cookies, NonHTTP)); + } Ok(()) } @@ -4176,8 +4182,7 @@ impl DocumentMethods for Document { node::from_untrusted_node_address(js_runtime, untrusted_node_address) }; DomRoot::downcast::(node) - }) - .collect(); + }).collect(); // Step 4 if let Some(root_element) = self.GetDocumentElement() { @@ -4191,117 +4196,149 @@ impl DocumentMethods for Document { } // https://html.spec.whatwg.org/multipage/#dom-document-open - fn Open( - &self, - _unused1: Option, - _unused2: Option, - ) -> Fallible> { - // Step 1 + fn Open(&self, _type: Option, replace: DOMString) -> Fallible> { if !self.is_html_document() { + // Step 1. return Err(Error::InvalidState); } - // Step 2 + // Step 2. if self.throw_on_dynamic_markup_insertion_counter.get() > 0 { return Err(Error::InvalidState); } - // Step 3 + if !self.is_active() { + // Step 3. + return Ok(DomRoot::from_ref(self)); + } + let entry_responsible_document = GlobalScope::entry().as_window().Document(); - // Step 4 // This check is same-origin not same-origin-domain. // https://github.com/whatwg/html/issues/2282 // https://github.com/whatwg/html/pull/2288 if !self.origin.same_origin(&entry_responsible_document.origin) { + // Step 4. return Err(Error::Security); } - // Step 5 if self .get_current_parser() .map_or(false, |parser| parser.is_active()) { + // Step 5. return Ok(DomRoot::from_ref(self)); } - // Step 6 - if self.is_prompting_or_unloading() { - return Ok(DomRoot::from_ref(self)); - } + // Step 6. + // TODO: ignore-opens-during-unload counter check. + + // Step 7, 8. + // TODO: check session history's state. + let replace = replace.eq_ignore_ascii_case("replace"); + + // Step 9. + // TODO: salvageable flag. + + // Step 10. + // TODO: prompt to unload. window_from_node(self).set_navigation_start(); - // Step 7 - // TODO: https://github.com/servo/servo/issues/21937 - if self.has_browsing_context() { - self.abort(); - } + // Step 11. + // TODO: unload. - // Step 8 + // Step 12. + self.abort(); + + // Step 13. for node in self.upcast::().traverse_preorder() { node.upcast::().remove_all_listeners(); } - // Step 9 - if self.window.Document() == DomRoot::from_ref(self) { - self.window.upcast::().remove_all_listeners(); - } + // Step 14. + // TODO: remove any tasks associated with the Document in any task source. - // Step 10 - // TODO: https://github.com/servo/servo/issues/21936 + // Step 15. Node::replace_all(None, self.upcast::()); - // Step 11 - if self.is_fully_active() { - let mut new_url = entry_responsible_document.url(); - if entry_responsible_document != DomRoot::from_ref(self) { - new_url.set_fragment(None); - } - // TODO: https://github.com/servo/servo/issues/21939 - self.set_url(new_url); - } + // Steps 16, 17. + // Let's not? + // TODO: https://github.com/whatwg/html/issues/1698 - // Step 12 - // TODO: https://github.com/servo/servo/issues/21938 + // Step 18. + self.implementation.set(None); + self.images.set(None); + self.embeds.set(None); + self.links.set(None); + self.forms.set(None); + self.scripts.set(None); + self.anchors.set(None); + self.applets.set(None); + *self.stylesheets.borrow_mut() = DocumentStylesheetSet::new(); + self.animation_frame_ident.set(0); + self.animation_frame_list.borrow_mut().clear(); + self.pending_restyles.borrow_mut().clear(); + self.target_element.set(None); + *self.last_click_info.borrow_mut() = None; - // Step 13 - self.set_quirks_mode(QuirksMode::NoQuirks); + // Step 19. + // TODO: Set the active document of document's browsing context to document with window. + + // Step 20. + // TODO: Replace document's singleton objects with new instances of those objects, created in window's Realm. + + // Step 21. + self.set_encoding(UTF_8); + + // Step 22. + // TODO: reload override buffer. + + // Step 23. + // TODO: salvageable flag. + + let url = entry_responsible_document.url(); + + // Step 24. + self.set_url(url.clone()); - // Step 14 + // Step 25. + // TODO: mute iframe load. + + // Step 26. let resource_threads = self .window .upcast::() .resource_threads() .clone(); *self.loader.borrow_mut() = - DocumentLoader::new_with_threads(resource_threads, Some(self.url())); - ServoParser::parse_html_script_input(self, self.url(), "text/html"); + DocumentLoader::new_with_threads(resource_threads, Some(url.clone())); + ServoParser::parse_html_script_input(self, url, "text/html"); - // Step 15 - self.ready_state.set(DocumentReadyState::Loading); + // Step 27. + self.ready_state.set(DocumentReadyState::Interactive); - // Step 16 - // Handled when creating the parser in step 14 + // Step 28. + // TODO: remove history traversal tasks. - // Step 17 - Ok(DomRoot::from_ref(self)) - } + // Step 29. + // TODO: truncate session history. - // https://html.spec.whatwg.org/multipage/#dom-document-open-window - fn Open_( - &self, - url: DOMString, - target: DOMString, - features: DOMString, - ) -> Fallible> { - // WhatWG spec states this should always return a WindowProxy, but the spec for WindowProxy.open states - // it optionally returns a WindowProxy. Assume an error if window.open returns none. - // See https://github.com/whatwg/html/issues/4091 - let context = self.browsing_context().ok_or(Error::InvalidAccess)?; - context - .open(url, target, features) - .ok_or(Error::InvalidAccess) + // Step 30. + // TODO: remove earlier entries. + + if !replace { + // Step 31. + // TODO: add history entry. + } + + // Step 32. + // TODO: clear fired unload flag. + + // Step 33 is handled when creating the parser in step 26. + + // Step 34. + Ok(DomRoot::from_ref(self)) } // https://html.spec.whatwg.org/multipage/#dom-document-write @@ -4327,14 +4364,13 @@ impl DocumentMethods for Document { // Either there is no parser, which means the parsing ended; // or script nesting level is 0, which means the method was // called from outside a parser-executed script. - if self.is_prompting_or_unloading() || - self.ignore_destructive_writes_counter.get() > 0 - { + if self.ignore_destructive_writes_counter.get() > 0 { // Step 4. + // TODO: handle ignore-opens-during-unload counter. return Ok(()); } // Step 5. - self.Open(None, None)?; + self.Open(None, "".into())?; self.get_current_parser().unwrap() }, }; @@ -4418,7 +4454,7 @@ impl DocumentMethods for Document { } fn update_with_current_time_ms(marker: &Cell) { - if marker.get() == 0 { + if marker.get() == Default::default() { let time = time::get_time(); let current_time_ms = time.sec * 1000 + time.nsec as i64 / 1000000; marker.set(current_time_ms as u64); diff --git a/components/script/dom/documentfragment.rs b/components/script/dom/documentfragment.rs index b347380e972f..444398700bcc 100644 --- a/components/script/dom/documentfragment.rs +++ b/components/script/dom/documentfragment.rs @@ -2,20 +2,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding; -use crate::dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::codegen::UnionTypes::NodeOrString; -use crate::dom::bindings::error::{ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::element::Element; -use crate::dom::htmlcollection::HTMLCollection; -use crate::dom::node::{window_from_node, Node}; -use crate::dom::nodelist::NodeList; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::DocumentFragmentBinding; +use dom::bindings::codegen::Bindings::DocumentFragmentBinding::DocumentFragmentMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::codegen::UnionTypes::NodeOrString; +use dom::bindings::error::{ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::element::Element; +use dom::htmlcollection::HTMLCollection; +use dom::node::{Node, window_from_node}; +use dom::nodelist::NodeList; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/documenttype.rs b/components/script/dom/documenttype.rs index 9ae3c05557b5..007790abe4d7 100644 --- a/components/script/dom/documenttype.rs +++ b/components/script/dom/documenttype.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DocumentTypeBinding; -use crate::dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods; -use crate::dom::bindings::codegen::UnionTypes::NodeOrString; -use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::DocumentTypeBinding; +use dom::bindings::codegen::Bindings::DocumentTypeBinding::DocumentTypeMethods; +use dom::bindings::codegen::UnionTypes::NodeOrString; +use dom::bindings::error::ErrorResult; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::node::Node; use dom_struct::dom_struct; // https://dom.spec.whatwg.org/#documenttype diff --git a/components/script/dom/domexception.rs b/components/script/dom/domexception.rs index e61f76caf96b..92debdc825e1 100644 --- a/components/script/dom/domexception.rs +++ b/components/script/dom/domexception.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding; -use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; -use crate::dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMExceptionBinding; +use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionConstants; +use dom::bindings::codegen::Bindings::DOMExceptionBinding::DOMExceptionMethods; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[repr(u16)] diff --git a/components/script/dom/domimplementation.rs b/components/script/dom/domimplementation.rs index 9c4703371170..f20cc61f3dfb 100644 --- a/components/script/dom/domimplementation.rs +++ b/components/script/dom/domimplementation.rs @@ -2,30 +2,29 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::document_loader::DocumentLoader; -use crate::dom::bindings::codegen::Bindings::DOMImplementationBinding; -use crate::dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementationMethods; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::{ - DocumentMethods, ElementCreationOptions, -}; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::xmlname::{namespace_from_domstring, validate_qualified_name}; -use crate::dom::document::DocumentSource; -use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; -use crate::dom::documenttype::DocumentType; -use crate::dom::htmlbodyelement::HTMLBodyElement; -use crate::dom::htmlheadelement::HTMLHeadElement; -use crate::dom::htmlhtmlelement::HTMLHtmlElement; -use crate::dom::htmltitleelement::HTMLTitleElement; -use crate::dom::node::Node; -use crate::dom::text::Text; -use crate::dom::xmldocument::XMLDocument; +use document_loader::DocumentLoader; +use dom::bindings::codegen::Bindings::DOMImplementationBinding; +use dom::bindings::codegen::Bindings::DOMImplementationBinding::DOMImplementationMethods; +use dom::bindings::codegen::Bindings::DocumentBinding::{DocumentMethods, ElementCreationOptions}; +use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::bindings::xmlname::{namespace_from_domstring, validate_qualified_name}; +use dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; +use dom::document::DocumentSource; +use dom::documenttype::DocumentType; +use dom::htmlbodyelement::HTMLBodyElement; +use dom::htmlheadelement::HTMLHeadElement; +use dom::htmlhtmlelement::HTMLHtmlElement; +use dom::htmltitleelement::HTMLTitleElement; +use dom::node::Node; +use dom::text::Text; +use dom::xmldocument::XMLDocument; use dom_struct::dom_struct; +use mime::{Mime, TopLevel, SubLevel}; use script_traits::DocumentActivity; // https://dom.spec.whatwg.org/#domimplementation @@ -83,9 +82,17 @@ impl DOMImplementationMethods for DOMImplementation { let namespace = namespace_from_domstring(maybe_namespace.to_owned()); let content_type = match namespace { - ns!(html) => "application/xhtml+xml".parse().unwrap(), - ns!(svg) => mime::IMAGE_SVG, - _ => "application/xml".parse().unwrap(), + ns!(html) => Mime( + TopLevel::Application, + SubLevel::Ext("xhtml+xml".to_string()), + vec![], + ), + ns!(svg) => Mime( + TopLevel::Image, + SubLevel::Ext("svg+xml".to_string()), + vec![], + ), + _ => Mime(TopLevel::Application, SubLevel::Xml, vec![]), }; // Step 1. diff --git a/components/script/dom/dommatrix.rs b/components/script/dom/dommatrix.rs index 4e4cf650f9ef..6e6a20987743 100644 --- a/components/script/dom/dommatrix.rs +++ b/components/script/dom/dommatrix.rs @@ -2,18 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::{ - DOMMatrixInit, DOMMatrixMethods, Wrap, -}; -use crate::dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::dommatrixreadonly::{ - dommatrixinit_to_matrix, entries_to_matrix, DOMMatrixReadOnly, -}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMMatrixBinding::{Wrap, DOMMatrixMethods, DOMMatrixInit}; +use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::DOMMatrixReadOnlyMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::dommatrixreadonly::{dommatrixinit_to_matrix, DOMMatrixReadOnly, entries_to_matrix}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use euclid::Transform3D; use js::rust::CustomAutoRooterGuard; @@ -299,8 +295,7 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-multiplyself fn MultiplySelf(&self, other: &DOMMatrixInit) -> Fallible> { // Steps 1-3. - self.upcast::() - .multiply_self(other) + self.upcast::().multiply_self(other) // Step 4. .and(Ok(DomRoot::from_ref(&self))) } @@ -308,8 +303,7 @@ impl DOMMatrixMethods for DOMMatrix { // https://drafts.fxtf.org/geometry-1/#dom-dommatrix-premultiplyself fn PreMultiplySelf(&self, other: &DOMMatrixInit) -> Fallible> { // Steps 1-3. - self.upcast::() - .pre_multiply_self(other) + self.upcast::().pre_multiply_self(other) // Step 4. .and(Ok(DomRoot::from_ref(&self))) } diff --git a/components/script/dom/dommatrixreadonly.rs b/components/script/dom/dommatrixreadonly.rs index 8edd62224804..a698ba811114 100644 --- a/components/script/dom/dommatrixreadonly.rs +++ b/components/script/dom/dommatrixreadonly.rs @@ -2,25 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::DOMMatrixBinding::{DOMMatrixInit, DOMMatrixMethods}; -use crate::dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{ - DOMMatrixReadOnlyMethods, Wrap, -}; -use crate::dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit; -use crate::dom::bindings::error; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::dommatrix::DOMMatrix; -use crate::dom::dompoint::DOMPoint; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::DOMMatrixBinding::{DOMMatrixInit, DOMMatrixMethods}; +use dom::bindings::codegen::Bindings::DOMMatrixReadOnlyBinding::{DOMMatrixReadOnlyMethods, Wrap}; +use dom::bindings::codegen::Bindings::DOMPointBinding::DOMPointInit; +use dom::bindings::error; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; +use dom::bindings::root::DomRoot; +use dom::dommatrix::DOMMatrix; +use dom::dompoint::DOMPoint; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use euclid::{Angle, Transform3D}; -use js::jsapi::{JSContext, JSObject}; +use euclid::{Transform3D, Angle}; +use js::jsapi::{JSObject, JSContext}; use js::rust::CustomAutoRooterGuard; -use js::typedarray::CreateWith; use js::typedarray::{Float32Array, Float64Array}; +use js::typedarray::CreateWith; use std::cell::{Cell, Ref}; use std::f64; use std::ptr; diff --git a/components/script/dom/domparser.rs b/components/script/dom/domparser.rs index 8ded7107698f..d2b5ac80b959 100644 --- a/components/script/dom/domparser.rs +++ b/components/script/dom/domparser.rs @@ -2,23 +2,23 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::document_loader::DocumentLoader; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; -use crate::dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::DocumentSource; -use crate::dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; -use crate::dom::servoparser::ServoParser; -use crate::dom::window::Window; +use document_loader::DocumentLoader; +use dom::bindings::codegen::Bindings::DOMParserBinding; +use dom::bindings::codegen::Bindings::DOMParserBinding::DOMParserMethods; +use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xhtml_xml; +use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Application_xml; +use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_html; +use dom::bindings::codegen::Bindings::DOMParserBinding::SupportedType::Text_xml; +use dom::bindings::codegen::Bindings::DocumentBinding::DocumentReadyState; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::document::{Document, HasBrowsingContext, IsHTMLDocument}; +use dom::document::DocumentSource; +use dom::servoparser::ServoParser; +use dom::window::Window; use dom_struct::dom_struct; use script_traits::DocumentActivity; diff --git a/components/script/dom/dompoint.rs b/components/script/dom/dompoint.rs index c0d89f8420de..ec0e96062bd1 100644 --- a/components/script/dom/dompoint.rs +++ b/components/script/dom/dompoint.rs @@ -2,15 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{ - DOMPointInit, DOMPointMethods, Wrap, -}; -use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods, Wrap}; +use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointReadOnlyMethods; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::dompointreadonly::{DOMPointReadOnly, DOMPointWriteMethods}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // http://dev.w3.org/fxtf/geometry/Overview.html#dompoint diff --git a/components/script/dom/dompointreadonly.rs b/components/script/dom/dompointreadonly.rs index ecda5c4e0b4d..28b3fea458f7 100644 --- a/components/script/dom/dompointreadonly.rs +++ b/components/script/dom/dompointreadonly.rs @@ -2,13 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{ - DOMPointReadOnlyMethods, Wrap, -}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::{DOMPointReadOnlyMethods, Wrap}; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; diff --git a/components/script/dom/domquad.rs b/components/script/dom/domquad.rs index f65088dde8da..b4270898d3f7 100644 --- a/components/script/dom/domquad.rs +++ b/components/script/dom/domquad.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods}; -use crate::dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; -use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::dompoint::DOMPoint; -use crate::dom::domrect::DOMRect; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMPointBinding::{DOMPointInit, DOMPointMethods}; +use dom::bindings::codegen::Bindings::DOMQuadBinding::{DOMQuadInit, DOMQuadMethods, Wrap}; +use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectInit; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::dompoint::DOMPoint; +use dom::domrect::DOMRect; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://drafts.fxtf.org/geometry/#DOMQuad diff --git a/components/script/dom/domrect.rs b/components/script/dom/domrect.rs index 6b149d171c01..cb5b3caadb95 100644 --- a/components/script/dom/domrect.rs +++ b/components/script/dom/domrect.rs @@ -2,14 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMRectBinding; -use crate::dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; -use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectReadOnlyMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::domrectreadonly::DOMRectReadOnly; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMRectBinding; +use dom::bindings::codegen::Bindings::DOMRectBinding::DOMRectMethods; +use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::DOMRectReadOnlyMethods; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::domrectreadonly::DOMRectReadOnly; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; #[dom_struct] diff --git a/components/script/dom/domrectreadonly.rs b/components/script/dom/domrectreadonly.rs index 96170f6a4896..86eeab0b2fdd 100644 --- a/components/script/dom/domrectreadonly.rs +++ b/components/script/dom/domrectreadonly.rs @@ -2,13 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{ - DOMRectReadOnlyMethods, Wrap, -}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::DOMRectReadOnlyBinding::{DOMRectReadOnlyMethods, Wrap}; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; diff --git a/components/script/dom/domstringmap.rs b/components/script/dom/domstringmap.rs index 10da1af92991..514781c9a1d1 100644 --- a/components/script/dom/domstringmap.rs +++ b/components/script/dom/domstringmap.rs @@ -2,14 +2,14 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; -use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; -use crate::dom::bindings::error::ErrorResult; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::window_from_node; +use dom::bindings::codegen::Bindings::DOMStringMapBinding; +use dom::bindings::codegen::Bindings::DOMStringMapBinding::DOMStringMapMethods; +use dom::bindings::error::ErrorResult; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::htmlelement::HTMLElement; +use dom::node::window_from_node; use dom_struct::dom_struct; #[dom_struct] diff --git a/components/script/dom/domtokenlist.rs b/components/script/dom/domtokenlist.rs index 902197795ff1..f1244ab49367 100644 --- a/components/script/dom/domtokenlist.rs +++ b/components/script/dom/domtokenlist.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding; -use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::element::Element; -use crate::dom::node::window_from_node; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::DOMTokenListBinding; +use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::element::Element; +use dom::node::window_from_node; use dom_struct::dom_struct; use html5ever::LocalName; use servo_atoms::Atom; diff --git a/components/script/dom/element.rs b/components/script/dom/element.rs index 38e5b1ae3c07..4144bb972ca3 100644 --- a/components/script/dom/element.rs +++ b/components/script/dom/element.rs @@ -4,102 +4,94 @@ //! Element nodes. -use crate::dom::activation::Activatable; -use crate::dom::attr::{Attr, AttrHelpersForLayout}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; -use crate::dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; -use crate::dom::bindings::codegen::Bindings::ElementBinding; -use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::codegen::Bindings::FunctionBinding::Function; -use crate::dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; -use crate::dom::bindings::codegen::UnionTypes::NodeOrString; -use crate::dom::bindings::conversions::DerivedFrom; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; -use crate::dom::bindings::refcounted::{Trusted, TrustedPromise}; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::xmlname::XMLName::InvalidXMLName; -use crate::dom::bindings::xmlname::{ - namespace_from_domstring, validate_and_extract, xml_name_type, -}; -use crate::dom::characterdata::CharacterData; -use crate::dom::create::create_element; -use crate::dom::customelementregistry::{ - CallbackReaction, CustomElementDefinition, CustomElementReaction, -}; -use crate::dom::document::{Document, LayoutDocumentHelpers}; -use crate::dom::documentfragment::DocumentFragment; -use crate::dom::domrect::DOMRect; -use crate::dom::domtokenlist::DOMTokenList; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlanchorelement::HTMLAnchorElement; -use crate::dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers}; -use crate::dom::htmlbuttonelement::HTMLButtonElement; -use crate::dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers}; -use crate::dom::htmlcollection::HTMLCollection; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; -use crate::dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers}; -use crate::dom::htmlformelement::FormControlElementHelpers; -use crate::dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers}; -use crate::dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods}; -use crate::dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers}; -use crate::dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers}; -use crate::dom::htmllabelelement::HTMLLabelElement; -use crate::dom::htmllegendelement::HTMLLegendElement; -use crate::dom::htmllinkelement::HTMLLinkElement; -use crate::dom::htmlobjectelement::HTMLObjectElement; -use crate::dom::htmloptgroupelement::HTMLOptGroupElement; -use crate::dom::htmlselectelement::HTMLSelectElement; -use crate::dom::htmlstyleelement::HTMLStyleElement; -use crate::dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers}; -use crate::dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers}; -use crate::dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers}; -use crate::dom::htmltablesectionelement::{ - HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers, -}; -use crate::dom::htmltemplateelement::HTMLTemplateElement; -use crate::dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; -use crate::dom::mutationobserver::{Mutation, MutationObserver}; -use crate::dom::namednodemap::NamedNodeMap; -use crate::dom::node::{document_from_node, window_from_node}; -use crate::dom::node::{ChildrenMutation, LayoutNodeHelpers, Node}; -use crate::dom::node::{NodeDamage, NodeFlags, UnbindContext}; -use crate::dom::nodelist::NodeList; -use crate::dom::promise::Promise; -use crate::dom::servoparser::ServoParser; -use crate::dom::text::Text; -use crate::dom::validation::Validatable; -use crate::dom::virtualmethods::{vtable_for, VirtualMethods}; -use crate::dom::window::ReflowReason; -use crate::script_thread::ScriptThread; -use crate::stylesheet_loader::StylesheetOwner; -use crate::task::TaskOnce; use devtools_traits::AttrInfo; +use dom::activation::Activatable; +use dom::attr::{Attr, AttrHelpersForLayout}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; +use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; +use dom::bindings::codegen::Bindings::ElementBinding; +use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::FunctionBinding::Function; +use dom::bindings::codegen::Bindings::HTMLTemplateElementBinding::HTMLTemplateElementMethods; +use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; +use dom::bindings::codegen::Bindings::WindowBinding::{ScrollBehavior, ScrollToOptions}; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::codegen::UnionTypes::NodeOrString; +use dom::bindings::conversions::DerivedFrom; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::{Castable, ElementTypeId, HTMLElementTypeId, NodeTypeId}; +use dom::bindings::refcounted::{Trusted, TrustedPromise}; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{Dom, DomRoot, LayoutDom, MutNullableDom, RootedReference}; +use dom::bindings::str::DOMString; +use dom::bindings::xmlname::{namespace_from_domstring, validate_and_extract, xml_name_type}; +use dom::bindings::xmlname::XMLName::InvalidXMLName; +use dom::characterdata::CharacterData; +use dom::create::create_element; +use dom::customelementregistry::{CallbackReaction, CustomElementDefinition, CustomElementReaction}; +use dom::document::{Document, LayoutDocumentHelpers}; +use dom::documentfragment::DocumentFragment; +use dom::domrect::DOMRect; +use dom::domtokenlist::DOMTokenList; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::htmlanchorelement::HTMLAnchorElement; +use dom::htmlbodyelement::{HTMLBodyElement, HTMLBodyElementLayoutHelpers}; +use dom::htmlbuttonelement::HTMLButtonElement; +use dom::htmlcanvaselement::{HTMLCanvasElement, LayoutHTMLCanvasElementHelpers}; +use dom::htmlcollection::HTMLCollection; +use dom::htmlelement::HTMLElement; +use dom::htmlfieldsetelement::HTMLFieldSetElement; +use dom::htmlfontelement::{HTMLFontElement, HTMLFontElementLayoutHelpers}; +use dom::htmlformelement::FormControlElementHelpers; +use dom::htmlhrelement::{HTMLHRElement, HTMLHRLayoutHelpers}; +use dom::htmliframeelement::{HTMLIFrameElement, HTMLIFrameElementLayoutMethods}; +use dom::htmlimageelement::{HTMLImageElement, LayoutHTMLImageElementHelpers}; +use dom::htmlinputelement::{HTMLInputElement, LayoutHTMLInputElementHelpers}; +use dom::htmllabelelement::HTMLLabelElement; +use dom::htmllegendelement::HTMLLegendElement; +use dom::htmllinkelement::HTMLLinkElement; +use dom::htmlobjectelement::HTMLObjectElement; +use dom::htmloptgroupelement::HTMLOptGroupElement; +use dom::htmlselectelement::HTMLSelectElement; +use dom::htmlstyleelement::HTMLStyleElement; +use dom::htmltablecellelement::{HTMLTableCellElement, HTMLTableCellElementLayoutHelpers}; +use dom::htmltableelement::{HTMLTableElement, HTMLTableElementLayoutHelpers}; +use dom::htmltablerowelement::{HTMLTableRowElement, HTMLTableRowElementLayoutHelpers}; +use dom::htmltablesectionelement::{HTMLTableSectionElement, HTMLTableSectionElementLayoutHelpers}; +use dom::htmltemplateelement::HTMLTemplateElement; +use dom::htmltextareaelement::{HTMLTextAreaElement, LayoutHTMLTextAreaElementHelpers}; +use dom::mutationobserver::{Mutation, MutationObserver}; +use dom::namednodemap::NamedNodeMap; +use dom::node::{ChildrenMutation, LayoutNodeHelpers, Node}; +use dom::node::{NodeDamage, NodeFlags, UnbindContext}; +use dom::node::{document_from_node, window_from_node}; +use dom::nodelist::NodeList; +use dom::promise::Promise; +use dom::servoparser::ServoParser; +use dom::text::Text; +use dom::validation::Validatable; +use dom::virtualmethods::{VirtualMethods, vtable_for}; +use dom::window::ReflowReason; use dom_struct::dom_struct; +use html5ever::{Prefix, LocalName, Namespace, QualName}; use html5ever::serialize; use html5ever::serialize::SerializeOpts; use html5ever::serialize::TraversalScope; use html5ever::serialize::TraversalScope::{ChildrenOnly, IncludeNode}; -use html5ever::{LocalName, Namespace, Prefix, QualName}; use js::jsapi::Heap; use js::jsval::JSVal; use msg::constellation_msg::InputMethodType; use net_traits::request::CorsSettings; use ref_filter_map::ref_filter_map; use script_layout_interface::message::ReflowGoal; -use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint}; +use script_thread::ScriptThread; +use selectors::Element as SelectorsElement; +use selectors::attr::{AttrSelectorOperation, NamespaceConstraint, CaseSensitivity}; use selectors::matching::{ElementSelectorFlags, MatchingContext}; use selectors::sink::Push; -use selectors::Element as SelectorsElement; use servo_arc::Arc; use servo_atoms::Atom; use std::borrow::Cow; @@ -109,28 +101,26 @@ use std::fmt; use std::mem; use std::rc::Rc; use std::str::FromStr; +use style::CaseSensitivityExt; use style::applicable_declarations::ApplicableDeclarationBlock; use style::attr::{AttrValue, LengthOrPercentageOrAuto}; use style::context::QuirksMode; use style::dom_apis; use style::element_state::ElementState; use style::invalidation::element::restyle_hints::RestyleHint; -use style::properties::longhands::{ - self, background_image, border_spacing, font_family, font_size, -}; -use style::properties::longhands::{overflow_x, overflow_y}; -use style::properties::{parse_style_attribute, PropertyDeclarationBlock}; use style::properties::{ComputedValues, Importance, PropertyDeclaration}; +use style::properties::{PropertyDeclarationBlock, parse_style_attribute}; +use style::properties::longhands::{self, background_image, border_spacing, font_family, font_size}; +use style::properties::longhands::{overflow_x, overflow_y}; use style::rule_tree::CascadeLevel; +use style::selector_parser::{NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser}; use style::selector_parser::extended_filtering; -use style::selector_parser::{ - NonTSPseudoClass, PseudoElement, RestyleDamage, SelectorImpl, SelectorParser, -}; -use style::shared_lock::{Locked, SharedRwLock}; +use style::shared_lock::{SharedRwLock, Locked}; use style::thread_state; -use style::values::{computed, specified}; use style::values::{CSSFloat, Either}; -use style::CaseSensitivityExt; +use style::values::{specified, computed}; +use stylesheet_loader::StylesheetOwner; +use task::TaskOnce; use xml5ever::serialize as xmlSerialize; use xml5ever::serialize::SerializeOpts as XmlSerializeOpts; use xml5ever::serialize::TraversalScope as XmlTraversalScope; @@ -466,8 +456,7 @@ pub unsafe fn get_attr_for_layout<'a>( .find(|attr| { let attr = attr.to_layout(); *name == attr.local_name_atom_forever() && (*attr.unsafe_get()).namespace() == namespace - }) - .map(|attr| attr.to_layout()) + }).map(|attr| attr.to_layout()) } #[allow(unsafe_code)] @@ -502,8 +491,7 @@ impl RawLayoutElementHelpers for Element { } else { None } - }) - .collect() + }).collect() } } @@ -514,7 +502,7 @@ pub trait LayoutElementHelpers { unsafe fn get_classes_for_layout(&self) -> Option<&'static [Atom]>; #[allow(unsafe_code)] - unsafe fn synthesize_presentational_hints_for_legacy_attributes(&self, _: &mut V) + unsafe fn synthesize_presentational_hints_for_legacy_attributes(&self, &mut V) where V: Push; #[allow(unsafe_code)] @@ -2026,8 +2014,7 @@ impl ElementMethods for Element { rect.size.width.to_f64_px(), rect.size.height.to_f64_px(), ) - }) - .collect() + }).collect() } // https://drafts.csswg.org/cssom-view/#dom-element-getboundingclientrect @@ -2579,8 +2566,8 @@ impl ElementMethods for Element { } impl VirtualMethods for Element { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool { @@ -2779,7 +2766,9 @@ impl<'a> SelectorsElement for DomRoot { #[allow(unsafe_code)] fn opaque(&self) -> ::selectors::OpaqueElement { - ::selectors::OpaqueElement::new(unsafe { &*self.reflector().get_jsobject().get() }) + ::selectors::OpaqueElement::new(unsafe { + &*self.reflector().get_jsobject().get() + }) } fn parent_element(&self) -> Option> { @@ -2941,31 +2930,31 @@ impl<'a> SelectorsElement for DomRoot { } impl Element { - pub fn as_maybe_activatable(&self) -> Option<&dyn Activatable> { + pub fn as_maybe_activatable(&self) -> Option<&Activatable> { let element = match self.upcast::().type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Activatable) + Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Activatable) + Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLAnchorElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Activatable) + Some(element as &Activatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLLabelElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Activatable) + Some(element as &Activatable) }, _ => None, }; @@ -2978,50 +2967,50 @@ impl Element { }) } - pub fn as_stylesheet_owner(&self) -> Option<&dyn StylesheetOwner> { + pub fn as_stylesheet_owner(&self) -> Option<&StylesheetOwner> { if let Some(s) = self.downcast::() { - return Some(s as &dyn StylesheetOwner); + return Some(s as &StylesheetOwner); } if let Some(l) = self.downcast::() { - return Some(l as &dyn StylesheetOwner); + return Some(l as &StylesheetOwner); } None } // https://html.spec.whatwg.org/multipage/#category-submit - pub fn as_maybe_validatable(&self) -> Option<&dyn Validatable> { + pub fn as_maybe_validatable(&self) -> Option<&Validatable> { let element = match self.upcast::().type_id() { NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLInputElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Validatable) + Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLButtonElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Validatable) + Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLObjectElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Validatable) + Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLSelectElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Validatable) + Some(element as &Validatable) }, NodeTypeId::Element(ElementTypeId::HTMLElement( HTMLElementTypeId::HTMLTextAreaElement, )) => { let element = self.downcast::().unwrap(); - Some(element as &dyn Validatable) + Some(element as &Validatable) }, _ => None, }; @@ -3113,8 +3102,7 @@ impl Element { }) // TODO: Check meta tags for a pragma-set default language // TODO: Check HTTP Content-Language header - }) - .next() + }).next() .unwrap_or(String::new()) } diff --git a/components/script/dom/errorevent.rs b/components/script/dom/errorevent.rs index f74b770557e7..3056175f89f6 100644 --- a/components/script/dom/errorevent.rs +++ b/components/script/dom/errorevent.rs @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::ErrorEventBinding; -use crate::dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::RootedTraceableBox; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::ErrorEventBinding; +use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::bindings::trace::RootedTraceableBox; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext}; use js::jsval::JSVal; diff --git a/components/script/dom/event.rs b/components/script/dom/event.rs index a1d0081cdf8b..46150cee78c2 100644 --- a/components/script/dom/event.rs +++ b/components/script/dom/event.rs @@ -2,28 +2,29 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::callback::ExceptionHandling; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::EventBinding; -use crate::dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::node::Node; -use crate::dom::virtualmethods::vtable_for; -use crate::dom::window::Window; -use crate::task::TaskOnce; use devtools_traits::{TimelineMarker, TimelineMarkerType}; +use dom::bindings::callback::ExceptionHandling; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::EventBinding; +use dom::bindings::codegen::Bindings::EventBinding::{EventConstants, EventMethods}; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::eventtarget::{CompiledEventListener, EventTarget, ListenerPhase}; +use dom::globalscope::GlobalScope; +use dom::node::Node; +use dom::virtualmethods::vtable_for; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; use std::cell::Cell; use std::default::Default; +use task::TaskOnce; +use time; #[dom_struct] pub struct Event { diff --git a/components/script/dom/eventsource.rs b/components/script/dom/eventsource.rs index b77cb5c34b2f..574b39e06235 100644 --- a/components/script/dom/eventsource.rs +++ b/components/script/dom/eventsource.rs @@ -2,46 +2,45 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::EventSourceBinding::{ - EventSourceInit, EventSourceMethods, Wrap, -}; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::messageevent::MessageEvent; -use crate::fetch::FetchCanceller; -use crate::network_listener::{NetworkListener, PreInvoke}; -use crate::task_source::{TaskSource, TaskSourceName}; -use crate::timers::OneshotTimerCallback; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::EventSourceBinding::{EventSourceInit, EventSourceMethods, Wrap}; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::messageevent::MessageEvent; use dom_struct::dom_struct; use euclid::Length; -use headers_ext::ContentType; -use http::header::{self, HeaderName, HeaderValue}; +use fetch::FetchCanceller; +use hyper::header::{Accept, qitem}; use ipc_channel::ipc; use ipc_channel::router::ROUTER; use js::conversions::ToJSValConvertible; use js::jsapi::JSAutoCompartment; use js::jsval::UndefinedValue; -use mime::{self, Mime}; +use mime::{Mime, TopLevel, SubLevel}; +use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata}; +use net_traits::{FetchResponseMsg, FetchResponseListener, NetworkError}; use net_traits::request::{CacheMode, CorsSettings, CredentialsMode}; use net_traits::request::{RequestInit, RequestMode}; -use net_traits::{CoreResourceMsg, FetchChannels, FetchMetadata}; -use net_traits::{FetchResponseListener, FetchResponseMsg, NetworkError}; +use network_listener::{NetworkListener, PreInvoke}; use servo_atoms::Atom; use servo_url::ServoUrl; use std::cell::Cell; use std::mem; use std::str::{Chars, FromStr}; use std::sync::{Arc, Mutex}; +use task_source::{TaskSource, TaskSourceName}; +use timers::OneshotTimerCallback; use utf8; +header! { (LastEventId, "Last-Event-ID") => [String] } + const DEFAULT_RECONNECTION_TIME: u64 = 5000; #[derive(Clone, Copy, Debug, JSTraceable, MallocSizeOf, PartialEq)] @@ -180,10 +179,8 @@ impl EventSourceContext { self.data.push('\n'); }, "id" => mem::swap(&mut self.last_event_id, &mut self.value), - "retry" => { - if let Ok(time) = u64::from_str(&self.value) { - self.event_source.root().reconnection_time.set(time); - } + "retry" => if let Ok(time) = u64::from_str(&self.value) { + self.event_source.root().reconnection_time.set(time); }, _ => (), } @@ -341,15 +338,12 @@ impl FetchResponseListener for EventSourceContext { }; match meta.content_type { None => self.fail_the_connection(), - Some(ct) => { - if >::into(ct.into_inner()) == - mime::TEXT_EVENT_STREAM - { - self.origin = meta.final_url.origin().ascii_serialization(); + Some(ct) => match ct.into_inner().0 { + Mime(TopLevel::Text, SubLevel::EventStream, _) => { + self.origin = meta.final_url.origin().unicode_serialization(); self.announce_the_connection(); - } else { - self.fail_the_connection() - } + }, + _ => self.fail_the_connection(), }, } }, @@ -507,11 +501,9 @@ impl EventSource { ..RequestInit::default() }; // Step 10 - // TODO(eijebong): Replace once typed headers allow it - request.headers.insert( - header::ACCEPT, - HeaderValue::from_static("text/event-stream"), - ); + request + .headers + .set(Accept(vec![qitem(mime!(Text / EventStream))])); // Step 11 request.cache_mode = CacheMode::NoStore; // Step 12 @@ -551,8 +543,7 @@ impl EventSource { .send(CoreResourceMsg::Fetch( request, FetchChannels::ResponseMsg(action_sender, Some(cancel_receiver)), - )) - .unwrap(); + )).unwrap(); // Step 13 Ok(ev) } @@ -622,12 +613,9 @@ impl EventSourceTimeoutCallback { let mut request = event_source.request(); // Step 5.3 if !event_source.last_event_id.borrow().is_empty() { - //TODO(eijebong): Change this once typed header support custom values - request.headers.insert( - HeaderName::from_static("last-event-id"), - HeaderValue::from_str(&String::from(event_source.last_event_id.borrow().clone())) - .unwrap(), - ); + request.headers.set(LastEventId(String::from( + event_source.last_event_id.borrow().clone(), + ))); } // Step 5.4 global @@ -635,7 +623,6 @@ impl EventSourceTimeoutCallback { .send(CoreResourceMsg::Fetch( request, FetchChannels::ResponseMsg(self.action_sender, None), - )) - .unwrap(); + )).unwrap(); } } diff --git a/components/script/dom/eventtarget.rs b/components/script/dom/eventtarget.rs index a9cdbb07ea94..e012f2f13ff3 100644 --- a/components/script/dom/eventtarget.rs +++ b/components/script/dom/eventtarget.rs @@ -2,46 +2,46 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::beforeunloadevent::BeforeUnloadEvent; -use crate::dom::bindings::callback::{CallbackContainer, CallbackFunction, ExceptionHandling}; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; -use crate::dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; -use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::OnBeforeUnloadEventHandlerNonNull; -use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull; -use crate::dom::bindings::codegen::Bindings::EventListenerBinding::EventListener; -use crate::dom::bindings::codegen::Bindings::EventTargetBinding::AddEventListenerOptions; -use crate::dom::bindings::codegen::Bindings::EventTargetBinding::EventListenerOptions; -use crate::dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; -use crate::dom::bindings::codegen::Bindings::EventTargetBinding::Wrap; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::codegen::UnionTypes::AddEventListenerOptionsOrBoolean; -use crate::dom::bindings::codegen::UnionTypes::EventListenerOptionsOrBoolean; -use crate::dom::bindings::codegen::UnionTypes::EventOrString; -use crate::dom::bindings::error::{report_pending_exception, Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::element::Element; -use crate::dom::errorevent::ErrorEvent; -use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::node::document_from_node; -use crate::dom::virtualmethods::VirtualMethods; -use crate::dom::window::Window; +use dom::beforeunloadevent::BeforeUnloadEvent; +use dom::bindings::callback::{CallbackContainer, ExceptionHandling, CallbackFunction}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BeforeUnloadEventBinding::BeforeUnloadEventMethods; +use dom::bindings::codegen::Bindings::ErrorEventBinding::ErrorEventMethods; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; +use dom::bindings::codegen::Bindings::EventHandlerBinding::OnBeforeUnloadEventHandlerNonNull; +use dom::bindings::codegen::Bindings::EventHandlerBinding::OnErrorEventHandlerNonNull; +use dom::bindings::codegen::Bindings::EventListenerBinding::EventListener; +use dom::bindings::codegen::Bindings::EventTargetBinding::AddEventListenerOptions; +use dom::bindings::codegen::Bindings::EventTargetBinding::EventListenerOptions; +use dom::bindings::codegen::Bindings::EventTargetBinding::EventTargetMethods; +use dom::bindings::codegen::Bindings::EventTargetBinding::Wrap; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::codegen::UnionTypes::AddEventListenerOptionsOrBoolean; +use dom::bindings::codegen::UnionTypes::EventListenerOptionsOrBoolean; +use dom::bindings::codegen::UnionTypes::EventOrString; +use dom::bindings::error::{Error, Fallible, report_pending_exception}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::element::Element; +use dom::errorevent::ErrorEvent; +use dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; +use dom::globalscope::GlobalScope; +use dom::node::document_from_node; +use dom::virtualmethods::VirtualMethods; +use dom::window::Window; use dom_struct::dom_struct; use fnv::FnvHasher; -use js::jsapi::{JSAutoCompartment, JSFunction, JS_GetFunctionObject}; -use js::rust::wrappers::CompileFunction; +use js::jsapi::{JS_GetFunctionObject, JSAutoCompartment, JSFunction}; use js::rust::{AutoObjectVectorWrapper, CompileOptionsWrapper}; +use js::rust::wrappers::CompileFunction; use libc::{c_char, size_t}; use servo_atoms::Atom; use servo_url::ServoUrl; -use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::collections::HashMap; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::default::Default; use std::ffi::CString; use std::hash::BuildHasherDefault; @@ -302,8 +302,7 @@ impl EventListeners { } else { None } - }) - .collect() + }).collect() } fn has_listeners(&self) -> bool { @@ -733,7 +732,7 @@ impl EventTargetMethods for EventTarget { } impl VirtualMethods for EventTarget { - fn super_type(&self) -> Option<&dyn VirtualMethods> { + fn super_type(&self) -> Option<&VirtualMethods> { None } } diff --git a/components/script/dom/extendableevent.rs b/components/script/dom/extendableevent.rs index 80d2fb4dd080..4f7462746c22 100644 --- a/components/script/dom/extendableevent.rs +++ b/components/script/dom/extendableevent.rs @@ -2,15 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::EventBinding::{self, EventMethods}; -use crate::dom::bindings::codegen::Bindings::ExtendableEventBinding; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::Event; -use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; +use dom::bindings::codegen::Bindings::EventBinding::{self, EventMethods}; +use dom::bindings::codegen::Bindings::ExtendableEventBinding; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::event::Event; +use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::JSContext; use js::rust::HandleValue; diff --git a/components/script/dom/extendablemessageevent.rs b/components/script/dom/extendablemessageevent.rs index c7b2ce220913..0e3119db1f5b 100644 --- a/components/script/dom/extendablemessageevent.rs +++ b/components/script/dom/extendablemessageevent.rs @@ -2,19 +2,19 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::ExtendableMessageEventBinding; -use crate::dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::RootedTraceableBox; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::extendableevent::ExtendableEvent; -use crate::dom::globalscope::GlobalScope; -use crate::dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; +use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding; +use dom::bindings::codegen::Bindings::ExtendableMessageEventBinding::ExtendableMessageEventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::bindings::trace::RootedTraceableBox; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::extendableevent::ExtendableEvent; +use dom::globalscope::GlobalScope; +use dom::serviceworkerglobalscope::ServiceWorkerGlobalScope; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext}; use js::jsval::JSVal; diff --git a/components/script/dom/file.rs b/components/script/dom/file.rs index 85b877e1d3aa..47fd4920bb6f 100644 --- a/components/script/dom/file.rs +++ b/components/script/dom/file.rs @@ -2,19 +2,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::FileBinding; -use crate::dom::bindings::codegen::Bindings::FileBinding::FileMethods; -use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::blob::{blob_parts_to_bytes, Blob, BlobImpl}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::FileBinding; +use dom::bindings::codegen::Bindings::FileBinding::FileMethods; +use dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::blob::{Blob, BlobImpl, blob_parts_to_bytes}; +use dom::globalscope::GlobalScope; +use dom::window::Window; use dom_struct::dom_struct; use net_traits::filemanager_thread::SelectedFile; +use time; #[dom_struct] pub struct File { diff --git a/components/script/dom/filelist.rs b/components/script/dom/filelist.rs index 241305c71a4a..92d39e5b539e 100644 --- a/components/script/dom/filelist.rs +++ b/components/script/dom/filelist.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::FileListBinding; -use crate::dom::bindings::codegen::Bindings::FileListBinding::FileListMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::file::File; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::FileListBinding; +use dom::bindings::codegen::Bindings::FileListBinding::FileListMethods; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::file::File; +use dom::window::Window; use dom_struct::dom_struct; use std::slice::Iter; diff --git a/components/script/dom/filereader.rs b/components/script/dom/filereader.rs index c10f7688b404..c816c9433039 100644 --- a/components/script/dom/filereader.rs +++ b/components/script/dom/filereader.rs @@ -3,42 +3,40 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use base64; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; -use crate::dom::bindings::codegen::Bindings::FileReaderBinding::{ - self, FileReaderConstants, FileReaderMethods, -}; -use crate::dom::bindings::codegen::UnionTypes::StringOrObject; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::RootedTraceableBox; -use crate::dom::blob::Blob; -use crate::dom::domexception::{DOMErrorName, DOMException}; -use crate::dom::event::{Event, EventBubbles, EventCancelable}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::progressevent::ProgressEvent; -use crate::task::TaskCanceller; -use crate::task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; -use crate::task_source::{TaskSource, TaskSourceName}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; +use dom::bindings::codegen::Bindings::FileReaderBinding::{self, FileReaderConstants, FileReaderMethods}; +use dom::bindings::codegen::UnionTypes::StringOrObject; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::refcounted::Trusted; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::bindings::trace::RootedTraceableBox; +use dom::blob::Blob; +use dom::domexception::{DOMErrorName, DOMException}; +use dom::event::{Event, EventBubbles, EventCancelable}; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::progressevent::ProgressEvent; use dom_struct::dom_struct; use encoding_rs::{Encoding, UTF_8}; +use hyper::mime::{Attr, Mime}; use js::jsapi::Heap; use js::jsapi::JSAutoCompartment; use js::jsapi::JSContext; use js::jsapi::JSObject; use js::jsval::{self, JSVal}; use js::typedarray::{ArrayBuffer, CreateWith}; -use mime::{self, Mime}; use servo_atoms::Atom; use std::cell::Cell; use std::ptr; use std::sync::Arc; use std::thread; +use task::TaskCanceller; +use task_source::{TaskSource, TaskSourceName}; +use task_source::file_reading::{FileReadingTask, FileReadingTaskSource}; #[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] pub enum FileReaderFunction { @@ -117,10 +115,11 @@ impl FileReaderSharedFunctionality { // Step 4 & 5 encoding = encoding.or_else(|| { let resultmime = blob_type.parse::().ok(); - resultmime.and_then(|mime| { - mime.params() - .find(|(ref k, _)| &mime::CHARSET == k) - .and_then(|(_, ref v)| Encoding::for_label(v.as_ref().as_bytes())) + resultmime.and_then(|Mime(_, _, ref parameters)| { + parameters + .iter() + .find(|&&(ref k, _)| &Attr::Charset == k) + .and_then(|&(_, ref v)| Encoding::for_label(v.as_str().as_bytes())) }) }); @@ -467,8 +466,7 @@ impl FileReader { task_source, canceller, ) - }) - .expect("Thread spawning failed"); + }).expect("Thread spawning failed"); Ok(()) } diff --git a/components/script/dom/filereadersync.rs b/components/script/dom/filereadersync.rs index 9738cfed73b8..10095db49611 100644 --- a/components/script/dom/filereadersync.rs +++ b/components/script/dom/filereadersync.rs @@ -2,17 +2,15 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; -use crate::dom::bindings::codegen::Bindings::FileReaderSyncBinding::{ - FileReaderSyncBinding, FileReaderSyncMethods, -}; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::blob::Blob; -use crate::dom::filereader::FileReaderSharedFunctionality; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::BlobBinding::BlobMethods; +use dom::bindings::codegen::Bindings::FileReaderSyncBinding::{FileReaderSyncBinding, FileReaderSyncMethods}; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::blob::Blob; +use dom::filereader::FileReaderSharedFunctionality; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use js::jsapi::{JSContext, JSObject}; use js::typedarray::{ArrayBuffer, CreateWith}; @@ -102,8 +100,7 @@ impl FileReaderSyncMethods for FileReaderSync { cx, CreateWith::Slice(&blob_contents), array_buffer.handle_mut() - ) - .is_ok() + ).is_ok() ); Ok(NonNull::new_unchecked(array_buffer.get())) diff --git a/components/script/dom/focusevent.rs b/components/script/dom/focusevent.rs index f10f02412aeb..ce751df87544 100644 --- a/components/script/dom/focusevent.rs +++ b/components/script/dom/focusevent.rs @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::FocusEventBinding; -use crate::dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods; -use crate::dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::{EventBubbles, EventCancelable}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::uievent::UIEvent; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::FocusEventBinding; +use dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods; +use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{DomRoot, MutNullableDom, RootedReference}; +use dom::bindings::str::DOMString; +use dom::event::{EventBubbles, EventCancelable}; +use dom::eventtarget::EventTarget; +use dom::uievent::UIEvent; +use dom::window::Window; use dom_struct::dom_struct; use std::default::Default; diff --git a/components/script/dom/formdata.rs b/components/script/dom/formdata.rs index 3109b9c67d93..1ec80600ba4b 100644 --- a/components/script/dom/formdata.rs +++ b/components/script/dom/formdata.rs @@ -2,35 +2,35 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; -use crate::dom::bindings::codegen::Bindings::FormDataBinding::FormDataWrap; -use crate::dom::bindings::codegen::UnionTypes::FileOrUSVString; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::iterable::Iterable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::blob::{Blob, BlobImpl}; -use crate::dom::file::File; -use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlformelement::{FormDatum, FormDatumValue, HTMLFormElement}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::FormDataBinding::FormDataMethods; +use dom::bindings::codegen::Bindings::FormDataBinding::FormDataWrap; +use dom::bindings::codegen::UnionTypes::FileOrUSVString; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::iterable::Iterable; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::{DOMString, USVString}; +use dom::blob::{Blob, BlobImpl}; +use dom::file::File; +use dom::globalscope::GlobalScope; +use dom::htmlformelement::{HTMLFormElement, FormDatumValue, FormDatum}; use dom_struct::dom_struct; use html5ever::LocalName; -use std::collections::btree_map::Entry::{Occupied, Vacant}; -use std::collections::BTreeMap; +use std::collections::HashMap; +use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::iter; #[dom_struct] pub struct FormData { reflector_: Reflector, - data: DomRefCell>>, + data: DomRefCell>>, } impl FormData { fn new_inherited(opt_form: Option<&HTMLFormElement>) -> FormData { - let mut hashmap: BTreeMap> = BTreeMap::new(); + let mut hashmap: HashMap> = HashMap::new(); if let Some(form) = opt_form { for datum in form.get_form_dataset(None) { @@ -135,8 +135,7 @@ impl FormDataMethods for FormData { FormDatumValue::File(ref b) => { FileOrUSVString::File(DomRoot::from_ref(&*b)) }, - }) - .collect() + }).collect() }) } diff --git a/components/script/dom/gainnode.rs b/components/script/dom/gainnode.rs index 40754b7baf5f..7e2235f5e802 100644 --- a/components/script/dom/gainnode.rs +++ b/components/script/dom/gainnode.rs @@ -2,20 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::audionode::AudioNode; -use crate::dom::audioparam::AudioParam; -use crate::dom::baseaudiocontext::BaseAudioContext; -use crate::dom::bindings::codegen::Bindings::AudioNodeBinding::{ - ChannelCountMode, ChannelInterpretation, -}; -use crate::dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; -use crate::dom::bindings::codegen::Bindings::GainNodeBinding::{ - self, GainNodeMethods, GainOptions, -}; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::window::Window; +use dom::audionode::AudioNode; +use dom::audioparam::AudioParam; +use dom::baseaudiocontext::BaseAudioContext; +use dom::bindings::codegen::Bindings::AudioNodeBinding::{ChannelCountMode, ChannelInterpretation}; +use dom::bindings::codegen::Bindings::AudioParamBinding::AutomationRate; +use dom::bindings::codegen::Bindings::GainNodeBinding::{self, GainNodeMethods, GainOptions}; +use dom::bindings::error::Fallible; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::{Dom, DomRoot}; +use dom::window::Window; use dom_struct::dom_struct; use servo_media::audio::gain_node::GainNodeOptions; use servo_media::audio::node::AudioNodeInit; @@ -52,9 +48,9 @@ impl GainNode { node.node_id(), ParamType::Gain, AutomationRate::A_rate, - *options.gain, // default value - f32::MIN, // min value - f32::MAX, // max value + *options.gain, // default value + f32::MIN, // min value + f32::MAX, // max value ); Ok(GainNode { node, diff --git a/components/script/dom/gamepad.rs b/components/script/dom/gamepad.rs index 6994e16c4c45..d4858de99f86 100644 --- a/components/script/dom/gamepad.rs +++ b/components/script/dom/gamepad.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::GamepadBinding; -use crate::dom::bindings::codegen::Bindings::GamepadBinding::GamepadMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::gamepadbuttonlist::GamepadButtonList; -use crate::dom::gamepadevent::{GamepadEvent, GamepadEventType}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::vrpose::VRPose; +use dom::bindings::codegen::Bindings::GamepadBinding; +use dom::bindings::codegen::Bindings::GamepadBinding::GamepadMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::gamepadbuttonlist::GamepadButtonList; +use dom::gamepadevent::{GamepadEvent, GamepadEventType}; +use dom::globalscope::GlobalScope; +use dom::vrpose::VRPose; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext, JSObject}; -use js::typedarray::{CreateWith, Float64Array}; +use js::typedarray::{Float64Array, CreateWith}; use std::cell::Cell; use std::ptr; use std::ptr::NonNull; diff --git a/components/script/dom/gamepadbutton.rs b/components/script/dom/gamepadbutton.rs index 57d50994c75a..df28f9e6a8e3 100644 --- a/components/script/dom/gamepadbutton.rs +++ b/components/script/dom/gamepadbutton.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::GamepadButtonBinding; -use crate::dom::bindings::codegen::Bindings::GamepadButtonBinding::GamepadButtonMethods; -use crate::dom::bindings::num::Finite; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::GamepadButtonBinding; +use dom::bindings::codegen::Bindings::GamepadButtonBinding::GamepadButtonMethods; +use dom::bindings::num::Finite; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use std::cell::Cell; diff --git a/components/script/dom/gamepadbuttonlist.rs b/components/script/dom/gamepadbuttonlist.rs index 175b7c7aeeff..22e79c981002 100644 --- a/components/script/dom/gamepadbuttonlist.rs +++ b/components/script/dom/gamepadbuttonlist.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding; -use crate::dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot, RootedReference}; -use crate::dom::gamepadbutton::GamepadButton; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::codegen::Bindings::GamepadButtonListBinding; +use dom::bindings::codegen::Bindings::GamepadButtonListBinding::GamepadButtonListMethods; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, RootedReference}; +use dom::gamepadbutton::GamepadButton; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; use webvr_traits::WebVRGamepadButton; diff --git a/components/script/dom/gamepadevent.rs b/components/script/dom/gamepadevent.rs index c96c3e021bd2..b8bd371f0880 100644 --- a/components/script/dom/gamepadevent.rs +++ b/components/script/dom/gamepadevent.rs @@ -2,18 +2,18 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; -use crate::dom::bindings::codegen::Bindings::GamepadEventBinding; -use crate::dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::DOMString; -use crate::dom::event::Event; -use crate::dom::gamepad::Gamepad; -use crate::dom::globalscope::GlobalScope; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::EventBinding::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::GamepadEventBinding; +use dom::bindings::codegen::Bindings::GamepadEventBinding::GamepadEventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::event::Event; +use dom::gamepad::Gamepad; +use dom::globalscope::GlobalScope; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/gamepadlist.rs b/components/script/dom/gamepadlist.rs index b158cc3891cf..1e48e7560ea6 100644 --- a/components/script/dom/gamepadlist.rs +++ b/components/script/dom/gamepadlist.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::GamepadListBinding; -use crate::dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::gamepad::Gamepad; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::GamepadListBinding; +use dom::bindings::codegen::Bindings::GamepadListBinding::GamepadListMethods; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::gamepad::Gamepad; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; // https://www.w3.org/TR/gamepad/ diff --git a/components/script/dom/globalscope.rs b/components/script/dom/globalscope.rs index 5d2ed77ce4dd..62eae2dedae2 100644 --- a/components/script/dom/globalscope.rs +++ b/components/script/dom/globalscope.rs @@ -2,68 +2,67 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::EventSourceBinding::EventSourceBinding::EventSourceMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; -use crate::dom::bindings::conversions::root_from_object; -use crate::dom::bindings::error::{report_pending_exception, ErrorInfo}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::settings_stack::{entry_global, incumbent_global, AutoEntryScript}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::weakref::DOMTracker; -use crate::dom::crypto::Crypto; -use crate::dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; -use crate::dom::errorevent::ErrorEvent; -use crate::dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; -use crate::dom::eventsource::EventSource; -use crate::dom::eventtarget::EventTarget; -use crate::dom::performance::Performance; -use crate::dom::window::Window; -use crate::dom::workerglobalscope::WorkerGlobalScope; -use crate::dom::workletglobalscope::WorkletGlobalScope; -use crate::microtask::{Microtask, MicrotaskQueue}; -use crate::script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; -use crate::script_thread::{MainThreadScriptChan, ScriptThread}; -use crate::task::TaskCanceller; -use crate::task_source::dom_manipulation::DOMManipulationTaskSource; -use crate::task_source::file_reading::FileReadingTaskSource; -use crate::task_source::networking::NetworkingTaskSource; -use crate::task_source::performance_timeline::PerformanceTimelineTaskSource; -use crate::task_source::remote_event::RemoteEventTaskSource; -use crate::task_source::websocket::WebsocketTaskSource; -use crate::task_source::TaskSourceName; -use crate::timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; -use crate::timers::{OneshotTimers, TimerCallback}; use devtools_traits::{ScriptToDevtoolsControlMsg, WorkerId}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::EventSourceBinding::EventSourceBinding::EventSourceMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods; +use dom::bindings::conversions::root_from_object; +use dom::bindings::error::{ErrorInfo, report_pending_exception}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::settings_stack::{AutoEntryScript, entry_global, incumbent_global}; +use dom::bindings::str::DOMString; +use dom::bindings::weakref::DOMTracker; +use dom::crypto::Crypto; +use dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope; +use dom::errorevent::ErrorEvent; +use dom::event::{Event, EventBubbles, EventCancelable, EventStatus}; +use dom::eventsource::EventSource; +use dom::eventtarget::EventTarget; +use dom::performance::Performance; +use dom::window::Window; +use dom::workerglobalscope::WorkerGlobalScope; +use dom::workletglobalscope::WorkletGlobalScope; use dom_struct::dom_struct; use ipc_channel::ipc::IpcSender; +use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; use js::glue::{IsWrapper, UnwrapObject}; -use js::jsapi::JSObject; use js::jsapi::{CurrentGlobalOrNull, GetGlobalForObjectCrossCompartment}; -use js::jsapi::{HandleObject, Heap}; use js::jsapi::{JSAutoCompartment, JSContext}; +use js::jsapi::JSObject; use js::panic::maybe_resume_unwind; -use js::rust::wrappers::Evaluate2; -use js::rust::{get_object_class, CompileOptionsWrapper, Runtime}; +use js::rust::{CompileOptionsWrapper, Runtime, get_object_class}; use js::rust::{HandleValue, MutableHandleValue}; -use js::{JSCLASS_IS_DOMJSCLASS, JSCLASS_IS_GLOBAL}; +use js::rust::wrappers::Evaluate2; +use libc; +use microtask::{Microtask, MicrotaskQueue}; use msg::constellation_msg::PipelineId; -use net_traits::{CoreResourceThread, IpcSend, ResourceThreads}; -use profile_traits::{mem as profile_mem, time as profile_time}; +use net_traits::{CoreResourceThread, ResourceThreads, IpcSend}; +use profile_traits::{mem, time}; +use script_runtime::{CommonScriptMsg, ScriptChan, ScriptPort}; +use script_thread::{MainThreadScriptChan, ScriptThread}; use script_traits::{MsDuration, ScriptToConstellationChan, TimerEvent}; use script_traits::{TimerEventId, TimerSchedulerMsg, TimerSource}; use servo_url::{MutableOrigin, ServoUrl}; use std::cell::Cell; -use std::collections::hash_map::Entry; use std::collections::HashMap; +use std::collections::hash_map::Entry; use std::ffi::CString; use std::rc::Rc; -use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; -use time::{get_time, Timespec}; +use std::sync::atomic::{AtomicBool, Ordering}; +use task::TaskCanceller; +use task_source::TaskSourceName; +use task_source::file_reading::FileReadingTaskSource; +use task_source::networking::NetworkingTaskSource; +use task_source::performance_timeline::PerformanceTimelineTaskSource; +use task_source::remote_event::RemoteEventTaskSource; +use task_source::websocket::WebsocketTaskSource; +use time::{Timespec, get_time}; +use timers::{IsInterval, OneshotTimerCallback, OneshotTimerHandle}; +use timers::{OneshotTimers, TimerCallback}; #[derive(JSTraceable)] pub struct AutoCloseWorker(Arc); @@ -96,11 +95,11 @@ pub struct GlobalScope { /// For sending messages to the memory profiler. #[ignore_malloc_size_of = "channels are hard"] - mem_profiler_chan: profile_mem::ProfilerChan, + mem_profiler_chan: mem::ProfilerChan, /// For sending messages to the time profiler. #[ignore_malloc_size_of = "channels are hard"] - time_profiler_chan: profile_time::ProfilerChan, + time_profiler_chan: time::ProfilerChan, /// A handle for communicating messages to the constellation thread. #[ignore_malloc_size_of = "channels are hard"] @@ -136,31 +135,14 @@ pub struct GlobalScope { /// Vector storing references of all eventsources. event_source_tracker: DOMTracker, - - /// Storage for watching rejected promises waiting for some client to - /// consume their rejection. - /// Promises in this list have been rejected in the last turn of the - /// event loop without the rejection being handled. - /// Note that this can contain nullptrs in place of promises removed because - /// they're consumed before it'd be reported. - /// - /// - uncaught_rejections: DomRefCell>>>, - - /// Promises in this list have previously been reported as rejected - /// (because they were in the above list), but the rejection was handled - /// in the last turn of the event loop. - /// - /// - consumed_rejections: DomRefCell>>>, } impl GlobalScope { pub fn new_inherited( pipeline_id: PipelineId, devtools_chan: Option>, - mem_profiler_chan: profile_mem::ProfilerChan, - time_profiler_chan: profile_time::ProfilerChan, + mem_profiler_chan: mem::ProfilerChan, + time_profiler_chan: time::ProfilerChan, script_to_constellation_chan: ScriptToConstellationChan, scheduler_chan: IpcSender, resource_threads: ResourceThreads, @@ -187,8 +169,6 @@ impl GlobalScope { microtask_queue, list_auto_close_worker: Default::default(), event_source_tracker: DOMTracker::new(), - uncaught_rejections: Default::default(), - consumed_rejections: Default::default(), } } @@ -250,49 +230,6 @@ impl GlobalScope { GlobalScope::from_object(obj) } - pub fn add_uncaught_rejection(&self, rejection: HandleObject) { - self.uncaught_rejections - .borrow_mut() - .push(Heap::boxed(rejection.get())); - } - - pub fn remove_uncaught_rejection(&self, rejection: HandleObject) { - let mut uncaught_rejections = self.uncaught_rejections.borrow_mut(); - - if let Some(index) = uncaught_rejections - .iter() - .position(|promise| *promise == Heap::boxed(rejection.get())) - { - uncaught_rejections.remove(index); - } - } - - pub fn get_uncaught_rejections(&self) -> &DomRefCell>>> { - &self.uncaught_rejections - } - - pub fn add_consumed_rejection(&self, rejection: HandleObject) { - self.consumed_rejections - .borrow_mut() - .push(Heap::boxed(rejection.get())); - } - - pub fn remove_consumed_rejection(&self, rejection: HandleObject) { - let mut consumed_rejections = self.consumed_rejections.borrow_mut(); - - if let Some(index) = consumed_rejections - .iter() - .position(|promise| *promise == Heap::boxed(rejection.get())) - { - consumed_rejections.remove(index); - } - } - - pub fn get_consumed_rejections(&self) -> &DomRefCell>>> { - &self.consumed_rejections - } - - #[allow(unsafe_code)] pub fn get_cx(&self) -> *mut JSContext { Runtime::get() } @@ -346,12 +283,12 @@ impl GlobalScope { } /// Get a sender to the memory profiler thread. - pub fn mem_profiler_chan(&self) -> &profile_mem::ProfilerChan { + pub fn mem_profiler_chan(&self) -> &mem::ProfilerChan { &self.mem_profiler_chan } /// Get a sender to the time profiler thread. - pub fn time_profiler_chan(&self) -> &profile_time::ProfilerChan { + pub fn time_profiler_chan(&self) -> &time::ProfilerChan { &self.time_profiler_chan } @@ -462,7 +399,7 @@ impl GlobalScope { } /// `ScriptChan` to send messages to the event loop of this global scope. - pub fn script_chan(&self) -> Box { + pub fn script_chan(&self) -> Box { if let Some(window) = self.downcast::() { return MainThreadScriptChan(window.main_thread_script_chan().clone()).clone(); } @@ -522,17 +459,17 @@ impl GlobalScope { rval: MutableHandleValue, line_number: u32, ) -> bool { - let metadata = profile_time::TimerMetadata { + let metadata = time::TimerMetadata { url: if filename.is_empty() { self.get_url().as_str().into() } else { filename.into() }, - iframe: profile_time::TimerMetadataFrameType::RootWindow, - incremental: profile_time::TimerMetadataReflowType::FirstReflow, + iframe: time::TimerMetadataFrameType::RootWindow, + incremental: time::TimerMetadataReflowType::FirstReflow, }; - profile_time::profile( - profile_time::ProfilerCategory::ScriptEvaluate, + time::profile( + time::ProfilerCategory::ScriptEvaluate, Some(metadata), self.time_profiler_chan().clone(), || { @@ -648,10 +585,8 @@ impl GlobalScope { /// Perform a microtask checkpoint. pub fn perform_a_microtask_checkpoint(&self) { - self.microtask_queue.checkpoint( - |_| Some(DomRoot::from_ref(self)), - vec![DomRoot::from_ref(self)], - ); + self.microtask_queue + .checkpoint(|_| Some(DomRoot::from_ref(self))); } /// Enqueue a microtask for subsequent execution. @@ -662,7 +597,7 @@ impl GlobalScope { /// Create a new sender/receiver pair that can be used to implement an on-demand /// event loop. Used for implementing web APIs that require blocking semantics /// without resorting to nested event loops. - pub fn new_script_pair(&self) -> (Box, Box) { + pub fn new_script_pair(&self) -> (Box, Box) { if let Some(window) = self.downcast::() { return window.new_script_pair(); } @@ -689,16 +624,6 @@ impl GlobalScope { unreachable!(); } - pub fn dom_manipulation_task_source(&self) -> DOMManipulationTaskSource { - if let Some(window) = self.downcast::() { - return window.dom_manipulation_task_source(); - } - if let Some(worker) = self.downcast::() { - return worker.dom_manipulation_task_source(); - } - unreachable!(); - } - /// Channel to send messages to the file reading task source of /// this of this global scope. pub fn file_reading_task_source(&self) -> FileReadingTaskSource { diff --git a/components/script/dom/hashchangeevent.rs b/components/script/dom/hashchangeevent.rs index 4771f6d8d518..e32c64a779fb 100644 --- a/components/script/dom/hashchangeevent.rs +++ b/components/script/dom/hashchangeevent.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; -use crate::dom::bindings::codegen::Bindings::HashChangeEventBinding; -use crate::dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; -use crate::dom::bindings::error::Fallible; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::reflect_dom_object; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::event::Event; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::EventBinding::EventMethods; +use dom::bindings::codegen::Bindings::HashChangeEventBinding; +use dom::bindings::codegen::Bindings::HashChangeEventBinding::HashChangeEventMethods; +use dom::bindings::error::Fallible; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::reflect_dom_object; +use dom::bindings::root::DomRoot; +use dom::bindings::str::{DOMString, USVString}; +use dom::event::Event; +use dom::window::Window; use dom_struct::dom_struct; use servo_atoms::Atom; diff --git a/components/script/dom/headers.rs b/components/script/dom/headers.rs index c7c71fb7dde9..9ff08e7c07ab 100644 --- a/components/script/dom/headers.rs +++ b/components/script/dom/headers.rs @@ -2,22 +2,20 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::HeadersBinding::{ - HeadersInit, HeadersMethods, HeadersWrap, -}; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::iterable::Iterable; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::{is_token, ByteString}; -use crate::dom::globalscope::GlobalScope; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::HeadersBinding::{HeadersInit, HeadersMethods, HeadersWrap}; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::iterable::Iterable; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::{ByteString, is_token}; +use dom::globalscope::GlobalScope; use dom_struct::dom_struct; -use http::header::{self, HeaderMap as HyperHeaders, HeaderName, HeaderValue}; -use mime::{self, Mime}; +use hyper::header::Headers as HyperHeaders; +use mime::{Mime, TopLevel, SubLevel}; use std::cell::Cell; use std::result::Result; -use std::str::{self, FromStr}; +use std::str; #[dom_struct] pub struct Headers { @@ -89,19 +87,14 @@ impl HeadersMethods for Headers { } // Step 7 let mut combined_value: Vec = vec![]; - if let Some(v) = self - .header_list - .borrow() - .get(HeaderName::from_str(&valid_name).unwrap()) - { - combined_value = v.as_bytes().to_vec(); + if let Some(v) = self.header_list.borrow().get_raw(&valid_name) { + combined_value = v[0].clone(); combined_value.push(b','); } combined_value.extend(valid_value.iter().cloned()); - self.header_list.borrow_mut().insert( - HeaderName::from_str(&valid_name).unwrap(), - HeaderValue::from_bytes(&combined_value).unwrap(), - ); + self.header_list + .borrow_mut() + .set_raw(valid_name, vec![combined_value]); Ok(()) } @@ -128,19 +121,19 @@ impl HeadersMethods for Headers { return Ok(()); } // Step 6 - self.header_list.borrow_mut().remove(&valid_name); + self.header_list.borrow_mut().remove_raw(&valid_name); Ok(()) } // https://fetch.spec.whatwg.org/#dom-headers-get fn Get(&self, name: ByteString) -> Fallible> { // Step 1 - let valid_name = validate_name(name)?; + let valid_name = &validate_name(name)?; Ok(self .header_list .borrow() - .get(HeaderName::from_str(&valid_name).unwrap()) - .map(|v| ByteString::new(v.as_bytes().to_vec()))) + .get_raw(&valid_name) + .map(|v| ByteString::new(v[0].clone()))) } // https://fetch.spec.whatwg.org/#dom-headers-has @@ -148,7 +141,7 @@ impl HeadersMethods for Headers { // Step 1 let valid_name = validate_name(name)?; // Step 2 - Ok(self.header_list.borrow_mut().get(&valid_name).is_some()) + Ok(self.header_list.borrow_mut().get_raw(&valid_name).is_some()) } // https://fetch.spec.whatwg.org/#dom-headers-set @@ -178,10 +171,9 @@ impl HeadersMethods for Headers { } // Step 7 // https://fetch.spec.whatwg.org/#concept-header-list-set - self.header_list.borrow_mut().insert( - HeaderName::from_str(&valid_name).unwrap(), - HeaderValue::from_bytes(&valid_value).unwrap(), - ); + self.header_list + .borrow_mut() + .set_raw(valid_name, vec![valid_value]); Ok(()) } } @@ -192,10 +184,10 @@ impl Headers { match filler { // Step 1 Some(HeadersInit::Headers(h)) => { - for (name, value) in h.header_list.borrow().iter() { + for header in h.header_list.borrow().iter() { self.Append( - ByteString::new(Vec::from(name.as_str())), - ByteString::new(Vec::from(value.to_str().unwrap().as_bytes())), + ByteString::new(Vec::from(header.name())), + ByteString::new(Vec::from(header.value_string().into_bytes())), )?; } Ok(()) @@ -256,24 +248,26 @@ impl Headers { } pub fn get_headers_list(&self) -> HyperHeaders { - self.header_list.borrow_mut().clone() + let mut headers = HyperHeaders::new(); + headers.extend(self.header_list.borrow_mut().iter()); + headers } // https://fetch.spec.whatwg.org/#concept-header-extract-mime-type pub fn extract_mime_type(&self) -> Vec { self.header_list .borrow() - .get(header::CONTENT_TYPE) - .map_or(vec![], |v| v.as_bytes().to_owned()) + .get_raw("content-type") + .map_or(vec![], |v| v[0].clone()) } pub fn sort_header_list(&self) -> Vec<(String, String)> { let borrowed_header_list = self.header_list.borrow(); let headers_iter = borrowed_header_list.iter(); let mut header_vec = vec![]; - for (name, value) in headers_iter { - let name = name.as_str().to_owned(); - let value = value.to_str().unwrap().to_owned(); + for header in headers_iter { + let name = header.name().to_string(); + let value = header.value_string(); let name_value = (name, value); header_vec.push(name_value); } @@ -312,10 +306,10 @@ fn is_cors_safelisted_request_content_type(value: &[u8]) -> bool { let value_mime_result: Result = value_string.parse(); match value_mime_result { Err(_) => false, - Ok(value_mime) => match (value_mime.type_(), value_mime.subtype()) { - (mime::APPLICATION, mime::WWW_FORM_URLENCODED) | - (mime::MULTIPART, mime::FORM_DATA) | - (mime::TEXT, mime::PLAIN) => true, + Ok(value_mime) => match value_mime { + Mime(TopLevel::Application, SubLevel::WwwFormUrlEncoded, _) | + Mime(TopLevel::Multipart, SubLevel::FormData, _) | + Mime(TopLevel::Text, SubLevel::Plain, _) => true, _ => false, }, } diff --git a/components/script/dom/history.rs b/components/script/dom/history.rs index da0e1c325b81..ee5c38e8c89c 100644 --- a/components/script/dom/history.rs +++ b/components/script/dom/history.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HistoryBinding; -use crate::dom::bindings::codegen::Bindings::HistoryBinding::HistoryMethods; -use crate::dom::bindings::codegen::Bindings::LocationBinding::LocationBinding::LocationMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::error::{Error, ErrorResult, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, DomObject, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::bindings::structuredclone::StructuredCloneData; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::globalscope::GlobalScope; -use crate::dom::hashchangeevent::HashChangeEvent; -use crate::dom::popstateevent::PopStateEvent; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::HistoryBinding; +use dom::bindings::codegen::Bindings::HistoryBinding::HistoryMethods; +use dom::bindings::codegen::Bindings::LocationBinding::LocationBinding::LocationMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::{Error, ErrorResult, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{DomObject, Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot}; +use dom::bindings::str::{DOMString, USVString}; +use dom::bindings::structuredclone::StructuredCloneData; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::globalscope::GlobalScope; +use dom::hashchangeevent::HashChangeEvent; +use dom::popstateevent::PopStateEvent; +use dom::window::Window; use dom_struct::dom_struct; use js::jsapi::{Heap, JSContext}; use js::jsval::{JSVal, NullValue, UndefinedValue}; diff --git a/components/script/dom/htmlanchorelement.rs b/components/script/dom/htmlanchorelement.rs index efa96da7e0e6..f813a4026f44 100644 --- a/components/script/dom/htmlanchorelement.rs +++ b/components/script/dom/htmlanchorelement.rs @@ -2,28 +2,28 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::activation::Activatable; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; -use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; -use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods; -use crate::dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::document::Document; -use crate::dom::domtokenlist::DOMTokenList; -use crate::dom::element::Element; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmlimageelement::HTMLImageElement; -use crate::dom::mouseevent::MouseEvent; -use crate::dom::node::{document_from_node, Node}; -use crate::dom::urlhelper::UrlHelper; -use crate::dom::virtualmethods::VirtualMethods; +use dom::activation::Activatable; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; +use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; +use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding; +use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding::HTMLAnchorElementMethods; +use dom::bindings::codegen::Bindings::MouseEventBinding::MouseEventMethods; +use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::{DOMString, USVString}; +use dom::document::Document; +use dom::domtokenlist::DOMTokenList; +use dom::element::Element; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::htmlelement::HTMLElement; +use dom::htmlimageelement::HTMLImageElement; +use dom::mouseevent::MouseEvent; +use dom::node::{Node, document_from_node}; +use dom::urlhelper::UrlHelper; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; @@ -98,8 +98,8 @@ impl HTMLAnchorElement { } impl VirtualMethods for HTMLAnchorElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { @@ -319,7 +319,7 @@ impl HTMLAnchorElementMethods for HTMLAnchorElement { }, Some(ref url) => { // Step 3. - url.origin().ascii_serialization() + url.origin().unicode_serialization() }, }) } diff --git a/components/script/dom/htmlareaelement.rs b/components/script/dom/htmlareaelement.rs index 45532529808f..303b72a55f27 100644 --- a/components/script/dom/htmlareaelement.rs +++ b/components/script/dom/htmlareaelement.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::activation::Activatable; -use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; -use crate::dom::bindings::codegen::Bindings::HTMLAreaElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::domtokenlist::DOMTokenList; -use crate::dom::element::Element; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlanchorelement::follow_hyperlink; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, Node}; -use crate::dom::virtualmethods::VirtualMethods; +use dom::activation::Activatable; +use dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods; +use dom::bindings::codegen::Bindings::HTMLAreaElementBinding; +use dom::bindings::codegen::Bindings::HTMLAreaElementBinding::HTMLAreaElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::domtokenlist::DOMTokenList; +use dom::element::Element; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::htmlanchorelement::follow_hyperlink; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, document_from_node}; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use euclid::Point2D; use html5ever::{LocalName, Prefix}; @@ -285,8 +285,8 @@ impl HTMLAreaElement { } impl VirtualMethods for HTMLAreaElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { diff --git a/components/script/dom/htmlaudioelement.rs b/components/script/dom/htmlaudioelement.rs index 68ab802cbe1d..354e138089bb 100644 --- a/components/script/dom/htmlaudioelement.rs +++ b/components/script/dom/htmlaudioelement.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLAudioElementBinding; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::htmlmediaelement::HTMLMediaElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLAudioElementBinding; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::htmlmediaelement::HTMLMediaElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmlbaseelement.rs b/components/script/dom/htmlbaseelement.rs index 1fe171d5182f..fbda8679239b 100644 --- a/components/script/dom/htmlbaseelement.rs +++ b/components/script/dom/htmlbaseelement.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::element::{AttributeMutation, Element}; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, Node, UnbindContext}; -use crate::dom::virtualmethods::VirtualMethods; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::HTMLBaseElementBinding; +use dom::bindings::codegen::Bindings::HTMLBaseElementBinding::HTMLBaseElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::element::{AttributeMutation, Element}; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, UnbindContext, document_from_node}; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; @@ -108,8 +108,8 @@ impl HTMLBaseElementMethods for HTMLBaseElement { } impl VirtualMethods for HTMLBaseElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { diff --git a/components/script/dom/htmlbodyelement.rs b/components/script/dom/htmlbodyelement.rs index 61d11c54f9a0..da0c641e5c30 100644 --- a/components/script/dom/htmlbodyelement.rs +++ b/components/script/dom/htmlbodyelement.rs @@ -2,26 +2,25 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::HTMLBodyElementBinding::{ - self, HTMLBodyElementMethods, -}; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{DomRoot, LayoutDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{document_from_node, window_from_node, Node}; -use crate::dom::virtualmethods::VirtualMethods; use cssparser::RGBA; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::HTMLBodyElementBinding::{self, HTMLBodyElementMethods}; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{LayoutDom, DomRoot}; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; +use dom::eventtarget::EventTarget; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, document_from_node, window_from_node}; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use embedder_traits::EmbedderMsg; use html5ever::{LocalName, Prefix}; use servo_url::ServoUrl; use style::attr::AttrValue; +use time; /// How long we should wait before performing the initial reflow after `` is parsed, in /// nanoseconds. @@ -134,8 +133,8 @@ impl HTMLBodyElementLayoutHelpers for LayoutDom { } impl VirtualMethods for HTMLBodyElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_affects_presentational_hints(&self, attr: &Attr) -> bool { diff --git a/components/script/dom/htmlbrelement.rs b/components/script/dom/htmlbrelement.rs index fed712cabba5..87e5c0249012 100644 --- a/components/script/dom/htmlbrelement.rs +++ b/components/script/dom/htmlbrelement.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLBRElementBinding; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLBRElementBinding; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::htmlelement::HTMLElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmlbuttonelement.rs b/components/script/dom/htmlbuttonelement.rs index 2b58aaea7a0f..d404c13ff9da 100755 --- a/components/script/dom/htmlbuttonelement.rs +++ b/components/script/dom/htmlbuttonelement.rs @@ -2,34 +2,34 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::activation::{synthetic_click_activation, Activatable, ActivationSource}; -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::{DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::element::{AttributeMutation, Element}; -use crate::dom::event::Event; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmlfieldsetelement::HTMLFieldSetElement; -use crate::dom::htmlformelement::HTMLFormElement; -use crate::dom::htmlformelement::{FormControl, FormDatum, FormDatumValue}; -use crate::dom::htmlformelement::{FormSubmitter, ResetFrom, SubmittedFrom}; -use crate::dom::node::{document_from_node, window_from_node, Node, UnbindContext}; -use crate::dom::nodelist::NodeList; -use crate::dom::validation::Validatable; -use crate::dom::validitystate::{ValidationFlags, ValidityState}; -use crate::dom::virtualmethods::VirtualMethods; +use dom::activation::{Activatable, ActivationSource, synthetic_click_activation}; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::HTMLButtonElementBinding; +use dom::bindings::codegen::Bindings::HTMLButtonElementBinding::HTMLButtonElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::element::{AttributeMutation, Element}; +use dom::event::Event; +use dom::eventtarget::EventTarget; +use dom::htmlelement::HTMLElement; +use dom::htmlfieldsetelement::HTMLFieldSetElement; +use dom::htmlformelement::{FormControl, FormDatum, FormDatumValue}; +use dom::htmlformelement::{FormSubmitter, ResetFrom, SubmittedFrom}; +use dom::htmlformelement::HTMLFormElement; +use dom::node::{Node, UnbindContext, document_from_node, window_from_node}; +use dom::nodelist::NodeList; +use dom::validation::Validatable; +use dom::validitystate::{ValidityState, ValidationFlags}; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; use std::default::Default; use style::element_state::ElementState; -#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq)] +#[derive(Clone, Copy, JSTraceable, MallocSizeOf, PartialEq )] enum ButtonType { Submit, Reset, @@ -189,8 +189,8 @@ impl HTMLButtonElement { } impl VirtualMethods for HTMLButtonElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { diff --git a/components/script/dom/htmlcanvaselement.rs b/components/script/dom/htmlcanvaselement.rs index 62d336d2b692..00b04db7ee8c 100644 --- a/components/script/dom/htmlcanvaselement.rs +++ b/components/script/dom/htmlcanvaselement.rs @@ -3,44 +3,41 @@ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use base64; -use canvas_traits::canvas::{CanvasId, CanvasMsg, FromScriptMsg}; +use canvas_traits::canvas::{CanvasMsg, CanvasId, FromScriptMsg}; use canvas_traits::webgl::WebGLVersion; -use crate::dom::attr::Attr; -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::{ - HTMLCanvasElementMethods, RenderingContext, -}; -use crate::dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; -use crate::dom::bindings::conversions::ConversionResult; -use crate::dom::bindings::error::{Error, Fallible}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::DomObject; -use crate::dom::bindings::root::{Dom, DomRoot, LayoutDom}; -use crate::dom::bindings::str::{DOMString, USVString}; -use crate::dom::canvasrenderingcontext2d::{ - CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers, -}; -use crate::dom::document::Document; -use crate::dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; -use crate::dom::globalscope::GlobalScope; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{window_from_node, Node}; -use crate::dom::virtualmethods::VirtualMethods; -use crate::dom::webgl2renderingcontext::WebGL2RenderingContext; -use crate::dom::webglrenderingcontext::{ - LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext, -}; +use dom::attr::Attr; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::CanvasRenderingContext2DBinding::CanvasRenderingContext2DMethods; +use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding; +use dom::bindings::codegen::Bindings::HTMLCanvasElementBinding::{HTMLCanvasElementMethods, RenderingContext}; +use dom::bindings::codegen::Bindings::WebGLRenderingContextBinding::WebGLContextAttributes; +use dom::bindings::conversions::ConversionResult; +use dom::bindings::error::{Error, Fallible}; +use dom::bindings::inheritance::Castable; +use dom::bindings::num::Finite; +use dom::bindings::reflector::DomObject; +use dom::bindings::root::{Dom, DomRoot, LayoutDom}; +use dom::bindings::str::{DOMString, USVString}; +use dom::canvasrenderingcontext2d::{CanvasRenderingContext2D, LayoutCanvasRenderingContext2DHelpers}; +use dom::document::Document; +use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; +use dom::globalscope::GlobalScope; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, window_from_node}; +use dom::virtualmethods::VirtualMethods; +use dom::webgl2renderingcontext::WebGL2RenderingContext; +use dom::webglrenderingcontext::{LayoutCanvasWebGLRenderingContextHelpers, WebGLRenderingContext}; use dom_struct::dom_struct; -use euclid::{Rect, Size2D}; +use euclid::Size2D; use html5ever::{LocalName, Prefix}; -use image::png::PNGEncoder; use image::ColorType; +use image::png::PNGEncoder; use js::error::throw_type_error; use js::jsapi::JSContext; use js::rust::HandleValue; use offscreen_gl_context::GLContextAttributes; use profile_traits::ipc; +use ref_filter_map; use script_layout_interface::{HTMLCanvasData, HTMLCanvasDataSource}; use servo_config::prefs::PREFS; use std::cell::Ref; @@ -101,8 +98,8 @@ impl HTMLCanvasElement { } } - pub fn get_size(&self) -> Size2D { - Size2D::new(self.Width(), self.Height()) + pub fn get_size(&self) -> Size2D { + Size2D::new(self.Width() as i32, self.Height() as i32) } pub fn origin_is_clean(&self) -> bool { @@ -280,7 +277,7 @@ impl HTMLCanvasElement { self.Height() != 0 && self.Width() != 0 } - pub fn fetch_all_data(&self) -> Option<(Vec, Size2D)> { + pub fn fetch_all_data(&self) -> Option<(Vec, Size2D)> { let size = self.get_size(); if size.width == 0 || size.height == 0 { @@ -307,7 +304,7 @@ impl HTMLCanvasElement { // TODO: add a method in WebGL2RenderingContext to get the pixels. return None; }, - None => vec![0; size.height as usize * size.width as usize * 4], + None => vec![0; size.height as usize * size.width as usize * 4] }; Some((data, size)) @@ -358,8 +355,10 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { _quality: HandleValue, ) -> Fallible { // Step 1. - if !self.origin_is_clean() { - return Err(Error::Security); + if let Some(CanvasContext::Context2d(ref context)) = *self.context.borrow() { + if !context.origin_is_clean() { + return Err(Error::Security); + } } // Step 2. @@ -368,21 +367,28 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { } // Step 3. - let file = match *self.context.borrow() { + let raw_data = match *self.context.borrow() { Some(CanvasContext::Context2d(ref context)) => { - context.get_rect(Rect::from_size(self.get_size())) + let image_data = context.GetImageData( + Finite::wrap(0f64), + Finite::wrap(0f64), + Finite::wrap(self.Width() as f64), + Finite::wrap(self.Height() as f64), + )?; + image_data.get_data_array() }, Some(CanvasContext::WebGL(ref context)) => { - match context.get_image_data(self.get_size()) { + match context.get_image_data(self.Width(), self.Height()) { Some(data) => data, None => return Ok(USVString("data:,".into())), } }, - Some(CanvasContext::WebGL2(ref context)) => { - match context.base_context().get_image_data(self.get_size()) { - Some(data) => data, - None => return Ok(USVString("data:,".into())), - } + Some(CanvasContext::WebGL2(ref context)) => match context + .base_context() + .get_image_data(self.Width(), self.Height()) + { + Some(data) => data, + None => return Ok(USVString("data:,".into())), }, None => { // Each pixel is fully-transparent black. @@ -390,24 +396,25 @@ impl HTMLCanvasElementMethods for HTMLCanvasElement { }, }; - // FIXME: Only handle image/png for now. - let mut png = Vec::new(); - // FIXME(nox): https://github.com/PistonDevelopers/image-png/issues/86 - // FIXME(nox): https://github.com/PistonDevelopers/image-png/issues/87 - PNGEncoder::new(&mut png) - .encode(&file, self.Width(), self.Height(), ColorType::RGBA(8)) - .unwrap(); - let mut url = "data:image/png;base64,".to_owned(); - // FIXME(nox): Should this use base64::URL_SAFE? - // FIXME(nox): https://github.com/alicemaz/rust-base64/pull/56 - base64::encode_config_buf(&png, base64::STANDARD, &mut url); - Ok(USVString(url)) + // Only handle image/png for now. + let mime_type = "image/png"; + + let mut encoded = Vec::new(); + { + let encoder: PNGEncoder<&mut Vec> = PNGEncoder::new(&mut encoded); + encoder + .encode(&raw_data, self.Width(), self.Height(), ColorType::RGBA(8)) + .unwrap(); + } + + let encoded = base64::encode(&encoded); + Ok(USVString(format!("data:{};base64,{}", mime_type, encoded))) } } impl VirtualMethods for HTMLCanvasElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { @@ -444,9 +451,9 @@ impl<'a> From<&'a WebGLContextAttributes> for GLContextAttributes { } pub mod utils { - use crate::dom::window::Window; + use dom::window::Window; + use net_traits::image_cache::{ImageResponse, UsePlaceholder, ImageOrMetadataAvailable}; use net_traits::image_cache::CanRequestImages; - use net_traits::image_cache::{ImageOrMetadataAvailable, ImageResponse, UsePlaceholder}; use servo_url::ServoUrl; pub fn request_image_from_cache(window: &Window, url: ServoUrl) -> ImageResponse { diff --git a/components/script/dom/htmlcollection.rs b/components/script/dom/htmlcollection.rs index cc2256a67646..d94607635e46 100644 --- a/components/script/dom/htmlcollection.rs +++ b/components/script/dom/htmlcollection.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding; -use crate::dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::reflector::{reflect_dom_object, Reflector}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom}; -use crate::dom::bindings::str::DOMString; -use crate::dom::bindings::trace::JSTraceable; -use crate::dom::bindings::xmlname::namespace_from_domstring; -use crate::dom::element::Element; -use crate::dom::node::{document_from_node, Node}; -use crate::dom::window::Window; +use dom::bindings::codegen::Bindings::HTMLCollectionBinding; +use dom::bindings::codegen::Bindings::HTMLCollectionBinding::HTMLCollectionMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::reflector::{Reflector, reflect_dom_object}; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom}; +use dom::bindings::str::DOMString; +use dom::bindings::trace::JSTraceable; +use dom::bindings::xmlname::namespace_from_domstring; +use dom::element::Element; +use dom::node::{Node, document_from_node}; +use dom::window::Window; use dom_struct::dom_struct; use html5ever::{LocalName, QualName}; use servo_atoms::Atom; @@ -69,10 +69,7 @@ pub struct HTMLCollection { impl HTMLCollection { #[allow(unrooted_must_root)] - pub fn new_inherited( - root: &Node, - filter: Box, - ) -> HTMLCollection { + pub fn new_inherited(root: &Node, filter: Box) -> HTMLCollection { HTMLCollection { reflector_: Reflector::new(), root: Dom::from_ref(root), @@ -102,7 +99,7 @@ impl HTMLCollection { pub fn new( window: &Window, root: &Node, - filter: Box, + filter: Box, ) -> DomRoot { reflect_dom_object( Box::new(HTMLCollection::new_inherited(root, filter)), @@ -114,7 +111,7 @@ impl HTMLCollection { pub fn create( window: &Window, root: &Node, - filter: Box, + filter: Box, ) -> DomRoot { HTMLCollection::new(window, root, filter) } diff --git a/components/script/dom/htmldataelement.rs b/components/script/dom/htmldataelement.rs index 29ad49f13703..07a2d0f24422 100644 --- a/components/script/dom/htmldataelement.rs +++ b/components/script/dom/htmldataelement.rs @@ -2,13 +2,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLDataElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDataElementBinding::HTMLDataElementMethods; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLDataElementBinding; +use dom::bindings::codegen::Bindings::HTMLDataElementBinding::HTMLDataElementMethods; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::htmlelement::HTMLElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldatalistelement.rs b/components/script/dom/htmldatalistelement.rs index 9c58b94695a1..e99a9324520d 100644 --- a/components/script/dom/htmldatalistelement.rs +++ b/components/script/dom/htmldatalistelement.rs @@ -2,16 +2,16 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLDataListElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::element::Element; -use crate::dom::htmlcollection::{CollectionFilter, HTMLCollection}; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::htmloptionelement::HTMLOptionElement; -use crate::dom::node::{window_from_node, Node}; +use dom::bindings::codegen::Bindings::HTMLDataListElementBinding; +use dom::bindings::codegen::Bindings::HTMLDataListElementBinding::HTMLDataListElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::element::Element; +use dom::htmlcollection::{CollectionFilter, HTMLCollection}; +use dom::htmlelement::HTMLElement; +use dom::htmloptionelement::HTMLOptionElement; +use dom::node::{Node, window_from_node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldetailselement.rs b/components/script/dom/htmldetailselement.rs index 3f7021dc786a..b764b0174ca0 100644 --- a/components/script/dom/htmldetailselement.rs +++ b/components/script/dom/htmldetailselement.rs @@ -2,22 +2,22 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::refcounted::Trusted; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::element::AttributeMutation; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{window_from_node, Node}; -use crate::dom::virtualmethods::VirtualMethods; -use crate::task_source::TaskSource; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding; +use dom::bindings::codegen::Bindings::HTMLDetailsElementBinding::HTMLDetailsElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::refcounted::Trusted; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::element::AttributeMutation; +use dom::eventtarget::EventTarget; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, window_from_node}; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use std::cell::Cell; +use task_source::TaskSource; #[dom_struct] pub struct HTMLDetailsElement { @@ -62,8 +62,8 @@ impl HTMLDetailsElementMethods for HTMLDetailsElement { } impl VirtualMethods for HTMLDetailsElement { - fn super_type(&self) -> Option<&dyn VirtualMethods> { - Some(self.upcast::() as &dyn VirtualMethods) + fn super_type(&self) -> Option<&VirtualMethods> { + Some(self.upcast::() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { diff --git a/components/script/dom/htmldialogelement.rs b/components/script/dom/htmldialogelement.rs index 36edbefa9cbf..97643bf691fd 100644 --- a/components/script/dom/htmldialogelement.rs +++ b/components/script/dom/htmldialogelement.rs @@ -2,17 +2,17 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::cell::DomRefCell; -use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::element::Element; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::{window_from_node, Node}; +use dom::bindings::cell::DomRefCell; +use dom::bindings::codegen::Bindings::HTMLDialogElementBinding; +use dom::bindings::codegen::Bindings::HTMLDialogElementBinding::HTMLDialogElementMethods; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::element::Element; +use dom::eventtarget::EventTarget; +use dom::htmlelement::HTMLElement; +use dom::node::{Node, window_from_node}; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldirectoryelement.rs b/components/script/dom/htmldirectoryelement.rs index 7de2e1c4a6a6..541a8abfa03e 100644 --- a/components/script/dom/htmldirectoryelement.rs +++ b/components/script/dom/htmldirectoryelement.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLDirectoryElementBinding; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLDirectoryElementBinding; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::htmlelement::HTMLElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldivelement.rs b/components/script/dom/htmldivelement.rs index 90d462dcc353..3de1af4e568e 100644 --- a/components/script/dom/htmldivelement.rs +++ b/components/script/dom/htmldivelement.rs @@ -2,12 +2,12 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods}; -use crate::dom::bindings::root::DomRoot; -use crate::dom::bindings::str::DOMString; -use crate::dom::document::Document; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLDivElementBinding::{self, HTMLDivElementMethods}; +use dom::bindings::root::DomRoot; +use dom::bindings::str::DOMString; +use dom::document::Document; +use dom::htmlelement::HTMLElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmldlistelement.rs b/components/script/dom/htmldlistelement.rs index 05e8be1bb2a8..b63f0225095b 100644 --- a/components/script/dom/htmldlistelement.rs +++ b/components/script/dom/htmldlistelement.rs @@ -2,11 +2,11 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::bindings::codegen::Bindings::HTMLDListElementBinding; -use crate::dom::bindings::root::DomRoot; -use crate::dom::document::Document; -use crate::dom::htmlelement::HTMLElement; -use crate::dom::node::Node; +use dom::bindings::codegen::Bindings::HTMLDListElementBinding; +use dom::bindings::root::DomRoot; +use dom::document::Document; +use dom::htmlelement::HTMLElement; +use dom::node::Node; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; diff --git a/components/script/dom/htmlelement.rs b/components/script/dom/htmlelement.rs index 93b8e0995105..9279f8fdbe13 100644 --- a/components/script/dom/htmlelement.rs +++ b/components/script/dom/htmlelement.rs @@ -2,36 +2,36 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ -use crate::dom::activation::{synthetic_click_activation, ActivationSource}; -use crate::dom::attr::Attr; -use crate::dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; -use crate::dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; -use crate::dom::bindings::codegen::Bindings::HTMLElementBinding; -use crate::dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods; -use crate::dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; -use crate::dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; -use crate::dom::bindings::error::{Error, ErrorResult}; -use crate::dom::bindings::inheritance::Castable; -use crate::dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId}; -use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom, RootedReference}; -use crate::dom::bindings::str::DOMString; -use crate::dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; -use crate::dom::document::{Document, FocusType}; -use crate::dom::documentfragment::DocumentFragment; -use crate::dom::domstringmap::DOMStringMap; -use crate::dom::element::{AttributeMutation, Element}; -use crate::dom::eventtarget::EventTarget; -use crate::dom::htmlbodyelement::HTMLBodyElement; -use crate::dom::htmlbrelement::HTMLBRElement; -use crate::dom::htmlframesetelement::HTMLFrameSetElement; -use crate::dom::htmlhtmlelement::HTMLHtmlElement; -use crate::dom::htmlinputelement::{HTMLInputElement, InputType}; -use crate::dom::htmllabelelement::HTMLLabelElement; -use crate::dom::node::{document_from_node, window_from_node}; -use crate::dom::node::{Node, NodeFlags}; -use crate::dom::nodelist::NodeList; -use crate::dom::text::Text; -use crate::dom::virtualmethods::VirtualMethods; +use dom::activation::{ActivationSource, synthetic_click_activation}; +use dom::attr::Attr; +use dom::bindings::codegen::Bindings::ElementBinding::ElementMethods; +use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull; +use dom::bindings::codegen::Bindings::HTMLElementBinding; +use dom::bindings::codegen::Bindings::HTMLElementBinding::HTMLElementMethods; +use dom::bindings::codegen::Bindings::NodeBinding::NodeBinding::NodeMethods; +use dom::bindings::codegen::Bindings::WindowBinding::WindowMethods; +use dom::bindings::error::{Error, ErrorResult}; +use dom::bindings::inheritance::{ElementTypeId, HTMLElementTypeId, NodeTypeId}; +use dom::bindings::inheritance::Castable; +use dom::bindings::root::{Dom, DomRoot, MutNullableDom, RootedReference}; +use dom::bindings::str::DOMString; +use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner}; +use dom::document::{Document, FocusType}; +use dom::documentfragment::DocumentFragment; +use dom::domstringmap::DOMStringMap; +use dom::element::{AttributeMutation, Element}; +use dom::eventtarget::EventTarget; +use dom::htmlbodyelement::HTMLBodyElement; +use dom::htmlbrelement::HTMLBRElement; +use dom::htmlframesetelement::HTMLFrameSetElement; +use dom::htmlhtmlelement::HTMLHtmlElement; +use dom::htmlinputelement::{HTMLInputElement, InputType}; +use dom::htmllabelelement::HTMLLabelElement; +use dom::node::{Node, NodeFlags}; +use dom::node::{document_from_node, window_from_node}; +use dom::nodelist::NodeList; +use dom::text::Text; +use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use script_layout_interface::message::QueryMsg; @@ -672,8 +672,7 @@ impl HTMLElement { .filter_map(|attr| { let raw_name = attr.local_name(); to_camel_case(&raw_name) - }) - .collect() + }).collect() } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels @@ -685,17 +684,16 @@ impl HTMLElement { // Traverse ancestors for implicitly associated